I am working on e-commerce website, where I am using Google Tag Manager(GTM) to analyse the data flow. So now I need to send some e-commerce booking data to GTM. For single cart value all looks ok. But when multiple cart values are there,I am not able to format the data-layer array how I am in need of. Below code works for single cart value, please help me to do the same for multiple cart items.
foreach($_SESSION['test']['item'] as $key => $value) {
dataLayer.push({
'event': 'Thankspage',
'itemname': [
{
'name': '<?php echo $_SESSION['test']['item']['item-name']; ?>',
'itemCode': '<?php echo $_SESSION['test']['item']['itemCode']; ?>',
'price': '<?php echo $_SESSION['test']['item']['item-price']; ?>'
}],
'totalprice': '<?php echo $_SESSION['test']['total-price']; ?>',
});
}
I tried using this foreach loop but i will get 'event': 'Thankspage' multiple times, i need structure like below if there are multiple items:
dataLayer.push({
'event': 'Thankspage',
'itemname': [
{
'name': 'Business Analysis Essentials',
'itemCode': 'BA-ESS',
'price': '1145.00'
},
{
'name': 'BABOK Foundation',
'itemCode': 'CGABAB3FCD',
'price': '595.00'
}],
'totalprice': '1740.00'
});
please help me in this regard.
The problem is that you are sending the dataLayer for every iteration of your for loop, what you need to do is create the array first and then send all of the data together. For example (code below not tested):
var itemsArray = []; //initialize empty array
var totalPrice; //initialize total price
foreach($_SESSION['test']['item'] as $key => $value) {
//code below will add all items in the itemsArray (no push to GTM yet)
itemsArray.push(
{
'name': '<?php echo $_SESSION['test']['item']['item-name']; ?>',
'itemCode': '<?php echo $_SESSION['test']['item']['itemCode']; ?>',
'price': '<?php echo $_SESSION['test']['item']['item-price']; ?>'
}
});
totalPrice = '<?php echo $_SESSION['test']['total-price']; ?>';
}
//once all items are in the itemsArray we will push the event to dataLayer
dataLayer.push({
'event': 'Thankspage',
'itemname': itemsArray,
'totalprice': totalPrice,
});
Related
I am creating a custom plugin in WordPress admin and I want to use ajax call inside plugin. My plugin has different folders. I have written following scripts but its giving me 400 (bad request) error. I use latest wordpress.
I tried to get answer from other post but not able to find what is the issue here. When I am moving the code to function.php everything working but I dont want to use function.php.
The code below has been written in single php file ( say dahboard.php)
<?php
add_action( 'admin_footer', 'ajax_without_file' );
function ajax_without_file() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var dataVariable = {
'action': 'my_action_without_file', // your action name
'variable_name': "Some value" // some additional data to send
};
jQuery.ajax({
url: ajaxurl, // this will point to admin-ajax.php
type: 'POST',
data: dataVariable,
success: function (response) {
console.log(response);
}
});
});
</script>
<?php
}
add_action ('wp_ajax_my_action_without_file' , 'my_action_without_file');
add_action('wp_ajax_nopriv_my_action_without_file','my_action_without_file');
function my_action_without_file(){
echo json_encode($_POST);
wp_die();
}
?>
Try this. I've changed "ajaxurl" to <?php echo admin_url( 'admin-ajax.php' ); ?>
<?php
add_action( 'admin_footer', 'ajax_without_file' );
function ajax_without_file() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var dataVariable = {
'action': 'my_action_without_file', // your action name
'variable_name': "Some value" // some additional data to send
};
jQuery.ajax({
url: <?php echo admin_url( 'admin-ajax.php' ); ?>, // this will point to admin-ajax.php
type: 'POST',
data: dataVariable,
success: function (response) {
console.log(response);
}
});
});
</script>
<?php
}
add_action ('wp_ajax_my_action_without_file' , 'my_action_without_file');
add_action('wp_ajax_nopriv_my_action_without_file','my_action_without_file');
function my_action_without_file(){
echo json_encode($_POST);
wp_die();
}
?>
First, I want to say, I am new in code. Recently I find the Ecommerce Tracking is not working, of course missing Ecommerce Tracking code. I search a lot from Internet, still cannot figure out, who can help me, thanks a lot.
I find the follow code:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new
Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/gtag.js','ga');
ga('create', 'UA-88888888-1', 'auto');
ga('send', 'pageview');
ga('require', 'ecommerce');
ga('ecommerce:addTransaction', {
'id': '1234', // Transaction ID. Required.
'affiliation': 'Fresh Egg', // Affiliation or store name.
'revenue': '43.66', // Grand Total.
'shipping': '3', // Shipping.
'tax': '1.29' // Tax.
});
ga('ecommerce:addItem', {
'id': '1234', // Transaction ID. Required.
'name': 'Fresh Egg', // Product name. Required.
'sku': 'AB12345', // SKU/code.
'category': 'Blue eggs', // Category or variation.
'price': '22.33', // Unit price.
'quantity': '1' // Quantity.
});
ga('ecommerce:send');
</script>
I donot know how to change the date, like, what "1234" means? Is this a certain date or something in from the code? And others! I know this may be a very foolish question, but I really need your help! Thanks a lot!
First of all, make sure ecommerce plugin is enough for what you need or maybe you should use enhanced ecommerce plugin.
You need to change, dynamically, each value depending on the transaction that is being executed.
It will depend on the programming language your site uses. For example, in php your code could be something like this:
ga('ecommerce:addItem', {
'id': '<?php echo $transacion_id; ?>',
'name': '<?php echo $product_name; ?>',
'sku': '<?php echo $sku; ?>',
'category': '<?php echo $product_category; ?>',
'price': '<?php echo $product_price; ?>',
'quantity': '<?php echo $product_quantity; ?>'
});
Consider using Google Tag Manager to implement your Analytics Ecommerce
hi I'm trying without reload Woo-commerce Shop page product per page but its reload of selected number...
Now it's working but page reload then work I need to without reload of shop page
anybody help me
add_action('wp_head','theme_ajaxurl');
function theme_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action( 'wp_ajax_nopriv_dl_sort_by_page', 'woocommerce_catalog_per_page_ordering' );
add_action( 'wp_ajax_dl_sort_by_page', 'woocommerce_catalog_per_page_ordering' );
function woocommerce_catalog_per_page_ordering() {
?>
<form action="" method="POST" name="results">
<select name="woocommerce-sort-by-columns" id="woocommerce-sort-by-columns" class="sortby">
<?php
// This is where you can change the amounts per page that the user will use feel free to change the numbers and text as you want, in my case we had 4 products per row so I chose to have multiples of four for the user to select.
$shopCatalog_orderby = apply_filters('woocommerce_sortby_page', array(
'' => __('Products per page', 'woocommerce'),
'8' => __('8 per page', 'woocommerce'),
'16' => __('16 per page', 'woocommerce'),
'32' => __('32 per page', 'woocommerce'),
'-1' => __('View All', 'woocommerce'),
));
foreach ( $shopCatalog_orderby as $sort_id => $sort_name )
echo '<option value="' . $sort_id . '" ' . selected( $_SESSION['sortby'], $sort_id, false ) . ' >' . $sort_name . '</option>';
?>
</select>
</form>
<?php // Adrian's code
if (isset($_POST['woocommerce-sort-by-columns']) && (($_COOKIE['shop_pageResults'] <> $_POST['woocommerce-sort-by-columns']))) {
$currentProductsPerPage = $_POST['woocommerce-sort-by-columns'];
} else {
$currentProductsPerPage = $_COOKIE['shop_pageResults'];
}
?>
<script type="text/javascript">
jQuery('select.sortby>option[value="<?php echo $currentProductsPerPage; ?>"]').attr('selected', true);
</script>
<?php
}
// now we set our cookie if we need to
function dl_sort_by_page($count) {
if (isset($_COOKIE['shop_pageResults'])) { // if normal page load with cookie
$count = $_COOKIE['shop_pageResults'];
}
if (isset($_POST['woocommerce-sort-by-columns'])) { //if form submitted
setcookie('shop_pageResults', $_POST['woocommerce-sort-by-columns'], time()+1209600, '/', 'yourdomain.com', false); //this will fail if any part of page has been output- hope this works!
$count = $_POST['woocommerce-sort-by-columns'];
}
// else normal page load and no cookie
return $count;
}
add_filter('loop_shop_per_page','dl_sort_by_page');
Script Code
<script>
jQuery( document ).on( 'change', '#woocommerce-sort-by-columns', function(event) {
event.preventDefault();
var post_id = jQuery('select.sortby').val();
jQuery.ajax({
url : ajaxurl,
type : 'POST',
data : {
action : 'dl_sort_by_page'
},
success : function( response ) {
alert('ok');
}
});
})
</script>
How i can use Ajax in checkout page in woocommerce. I am trying to add custom pricing just before Payment in Order Review Page.
I have a check box when user will select the checkbox and pricing should be add in order.
Here is my code
function woocommerce_update_order_review() {
global $woocommerce;
$prc = strip_tags($woocommerce->cart->get_cart_total());
$priceValue = str_replace(",","",str_replace("#36;","",substr($prc,1)));
if($priceValue<=300 && $priceValue>200){
$rate_cost = 2.70;
}
else if($priceValue>300){
$extraDvalue = 2.70;
$extraVal = ceil(round(($priceValue-300),0)/100)*.90;
$newPr = $extraDvalue+$extraVal;
$rate_cost = $newPr;
}
if($priceValue>100){
$woocommerce->cart->add_fee( 'Declared value', $rate_cost, false, '' );
}
exit;
}
add_action('wp_ajax_woocommerce_update_order_review','woocommerce_update_order_review');
add_action('wp_ajax_nopriv_woocommerce_update_order_review','woocommerce_update_order_review');
JS CODE
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// This does the ajax request
jQuery.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {
action: 'woocommerce_update_order_review', check: 'check'
}
}).done(function(value) {
alert(value);
});
Please suggest is this possible or not ?
Thanks
I am trying to pass variable when user click on link to page single.php
Here is my code
<a href='#' id='8' class='clickme' style='font-weight:bold;color:white;font-size:16px;'>";
In function.php, I put this code:
/////////////////////////////////////////////////////////
add_action( 'wp_head', 'myajaxcall' );
function myajaxcall(){ ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery(".clickme").click( function() {
// We'll pass this variable to the PHP function example_ajax_request
var id = $('.clickme').attr('id');
// This does the ajax request
$.ajax({
url: <?php echo admin_url( 'admin-ajax.php'); ?>,
data: {
'action':'get_sidebar_request',
'page_id' : id
},
// beforeSend: function (jqXHR, settings)
// {
// alert( url = settings.url);
//},
success:function(data){
alert(data);
},
error: function(errorThrown){
//alert(errorThrown);
}
});
});
});
</script>
<?php }
add_action( 'wp_ajax_get_sidebar_request', 'idAjax' );
add_action( 'wp_ajax_nopriv_get_sidebar_request', 'idAjax' );
function idAjax()
{
require( get_template_directory() . '/single.php' );
}
/////////////////////////////////////////////////////////////////////
And in file `single.php, when I want to get the passed variable, I put this code:
$page_id=0;
$page_id = $_REQUEST['page_id'];
echo "page_id=".$page_id;
But the variable isn't passing to single.php. I try to echo it, and nothing happens.
Can you help me?
You can use Network tool in Google Chrome to debug and see sent/received data.
If "id" is not null when you send it, try to use $_POST to output your data in your php file, like this :
var_dump($_POST);
check this :
$.ajax({
url: <?php echo admin_url( 'admin-ajax.php'); ?>,
data: {
'action':'get_sidebar_request',
'page_id' : id
},
and add double quote to url value
$.ajax({
url: "<?php echo admin_url( 'admin-ajax.php'); ?>",
data: {
'action':'get_sidebar_request',
'page_id' : id
},
if you don't see your ajax call, it's a javascript error in your code.
Do you have any error in browser Console ?