how to capture dynamic conversion values on Google ads? - woocommerce

I am trying to get dynamic the order total price on my thankyou page(the page seeing the user after a successful order) to the google ads report through the goole-tag-manager chrome extension.
The google ads snippet I am using on my thankyou page is this:
*I have follow the google support before (https://support.google.com/google-ads/answer/6095947?hl=en)
<!-- Event snippet for Purchase conversion page -->
<script>
gtag('event', 'conversion', {
'send_to': 'My Conversion ID/My Conversion Label',
'value': 11.50,
'currency': 'EUR',
'transaction_id': ''
});
</script>
and the order total amount is the " 'value': 11.50, "
So instead of 11.50 I am placing the below code
document.querySelector("#cost>.woocommerce-Price-amount.amount").innerText.match(/^.{1}(.*).{0}/i)[1].trim();
so I can take the total for each order every time dynamicaly by scaning the dom, but doesn't work. Are my thoughts right? Is this the right way to do it by addin code manually on my site without use gootle tag manager? Any Ideas about how to do it?

Well its actually quite simple when you do it with php.
// Hook the function in head.
add_action('wp_head', 'bks_head_social_tracking_code');
function bks_head_social_tracking_code() {
// Check if its thank you page.
if(is_wc_endpoint_url( 'order-received' )) {
// Get order object.
$order = wc_get_order(get_query_var('order-received'));
// Get total.
$order_total = $order->get_total();
// Prepare.
$output = "
<script>
gtag('event', 'conversion', {
'send_to': 'My Conversion ID/My Conversion Label',
'value': ". $order_total .", // Use dynamically.
'currency': 'EUR',
'transaction_id': ''
});
</script>";
// echo.
echo $output;
}
}
You can make the currency dynamic too. You can use this to to get different kinds of data. https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/

Related

Moving Coupon error code to bottom of woocommerce checkout page [duplicate]

I would like to change the position of all the coupon code-related WooCommerce messages on the checkout page.
I have successfully moved the coupon code form from its original position (top of the checkout page) to after the order details table (woocommerce_review_order_before_payment hook).
But now the coupon code message placement does not make sense, especially for mobile users, therefore I would like to move all of the coupon code-related messages below the coupon form (at the woocommerce_review_order_before_payment hook).
However, it's important that only messages that are related to coupon codes get moved and not all of the messages.
Here's a list of all the WooCommerce messages that are related to coupon codes:
Message
Message type
When
Coupon code already applied!
woocommerce-error
When you try applying a coupon code that has already been applied to your order.
Coupon "coupon-code" does not exist!
woocommerce-error
When you try applying a nonexistent coupon code.
Please enter a coupon code.
woocommerce-error
When you try applying an empty coupon field.
Coupon has been removed.
woocommerce-message
When you successfully remove a coupon code from your order.
Coupon code applied successfully.
woocommerce-message
When you successfully apply a coupon code to your order.
Could someone please help out?
First, As per said #Pavel Vnukov nested forms are not supported and are not part of the w3c standard. so you have added preventDefault so default action should not be taken.
I have fixed some code changes to the #Pavel Vnukov code to work as per your need.
Try the below code.
(function($){
$('.woocommerce-form-coupon-toggle').remove();
$(document).on("click", 'button[name="apply_coupon"]', function(event) {
event.preventDefault();
$form = $('form[name="checkout"]');
$form.block({message:''});
var data = {
security: wc_checkout_params.apply_coupon_nonce,
coupon_code: $( 'input[name="coupon_code"]' ).val()
};
$.ajax({
type: 'POST',
url: wc_checkout_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'apply_coupon' ),
data: data,
success: function( code ) {
$( '.woocommerce-error, .woocommerce-message' ).remove();
$form.removeClass( 'processing' ).unblock();
if ( code ) {
$( 'button[name="apply_coupon"]' ).parent().after( code );
$( document.body ).trigger( 'update_checkout', { update_shipping_method: false } );
}
},
dataType: 'html'
});
});
})(jQuery);
Tested and Works
It looks like a duplication of Move coupon field after checkout payment in Woocommerce?
Standart coupon form can't be placed before confirmation button - because you will include form in form - nested forms are not supported and are not part of the w3c standard.
You can easily move coupon form after confirmation button. The best way to move coupon block to another place is to use code from above question:
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form');
add_action( 'woocommerce_review_order_before_payment', 'woocommerce_checkout_coupon_form' );
Another way is to remove coupon form from it standard position and create a custom input with a button. Than you need to add custom js code like from woocommerce source (wp-content/plugins/woocommerce/assets/js/frontend/checkout.js:536)
$(".custom_apply_coupon_code").on("click", function(event) {
var data = {
security: wc_checkout_params.apply_coupon_nonce,
coupon_code: $( 'input[name="coupon_code"]' ).val()
};
$.ajax({
type: 'POST',
url: wc_checkout_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'apply_coupon' ),
data: data,
success: function( code ) {
$( '.woocommerce-error, .woocommerce-message' ).remove();
$form.removeClass( 'processing' ).unblock();
if ( code ) {
$form.before( code );
$form.slideUp();
$( document.body ).trigger( 'update_checkout', { update_shipping_method: false } );
}
},
dataType: 'html'
});
});
Where code will include success or error message.

Custom dimension error - In about 10~15% of value is missed

Please understand that I am not good at English.
I set up the 'Custom dimension' to get user-ID.
var customerCode = ''; // This is going to be inserted when user log in.
gtag('config', 'UA-00000000-0', {
'optimize_id': 'GTM-XXXXXXX',
'user_id': customerCode,
'custom_map': {'dimension1': 'userId'}
});
gtag('event', 'userId_dimension', {'userId': customerCode, 'non_interaction': true});
However, in about 10~15% of all sessions, user-ID are always missed.
But all other index of Custom dimension are being 100% collected.
I checked it in BigQuery.
So, to figure out the cause of the problem, I set up to push the Event value that is same with 'Custom dimension'.
gtag('event', 'event', {
'event_category' : 'cdTest',
'event_action' : customerCode,
'event_label' : '',
'non_interaction' : true
});
As a result, The Event was 100% collected, but user-ID for Custom dimension was still missed in about 10~15%.
How can I fix this problem?

How to fix GA Event Tracking inserted through jQuery in footer not sending reports to Google?

I have a Wordpress site. I have a CTA Button created through a plugin which is MaxButton. With the use of my assigned class to such button, I inserted the Google Analytics Event Tracking onClick script through jQuery at the footer since there's no way I can implement that directly on the button. Here's the script of the button created by the plugin...
<a class="maxbutton-2 maxbutton maxbutton-free-report free-report" href="#freereport">
<span class="mb-text">Claim Now!</span>
</a>
...And here's the GA Event Tracking Script that I have inserted into the footer that will supposedly send report when a user clicks on the button...
(function($) {
/* For GA Event Tracking (Free Report CTA) */
$(".free-report").click(function() {
ga('send', 'event', 'Free Report', 'Claim Now', 'Free Report Claim', '0');
});
})( jQuery );
With such codes, I have tested the site daily to gather reports if the code works. However, it's been a week and yet I have not seen any increase of my Goals that are being set. Can anybody here help me out? I have checked the suggested and similar questions here at StackOverflow yet noting seems to answer my question. Please provide me answers rather than just marking it as a duplicate, since it's this site's purpose. Please.
GA SCRIPT:
var mi_version = '7.8.0';
var mi_track_user = false;
var mi_no_track_reason = 'Note: The site owner has disabled Google Analytics tracking for your user role.';
var disableStr = 'ga-disable-UA-xxxxxxxx-x';
/* Function to detect opted out users */
function __gaTrackerIsOptedOut() {
return document.cookie.indexOf(disableStr + '=true') > -1;
}
/* Disable tracking if the opt-out cookie exists. */
if ( __gaTrackerIsOptedOut() ) {
window[disableStr] = true;
}
/* Opt-out function */
function __gaTrackerOptout() {
document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
window[disableStr] = true;
}
if ( mi_track_user ) {
(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','//www.google-analytics.com/analytics.js','__gaTracker');
__gaTracker('create', 'UA-xxxxxxxx-x', 'auto');
__gaTracker('set', 'forceSSL', true);
__gaTracker('send','pageview');
} else {
console.log( "Note: The site owner has disabled Google Analytics tracking for your user role." );
(function() {
/* https://developers.google.com/analytics/devguides/collection/analyticsjs/ */
var noopfn = function() {
return null;
};
var noopnullfn = function() {
return null;
};
var Tracker = function() {
return null;
};
var p = Tracker.prototype;
p.get = noopfn;
p.set = noopfn;
p.send = noopfn;
var __gaTracker = function() {
var len = arguments.length;
if ( len === 0 ) {
return;
}
var f = arguments[len-1];
if ( typeof f !== 'object' || f === null || typeof f.hitCallback !== 'function' ) {
console.log( 'Not running function __gaTracker(' + arguments[0] + " ....) because you are not being tracked. " + mi_no_track_reason );
return;
}
try {
f.hitCallback();
} catch (ex) {
}
};
__gaTracker.create = function() {
return new Tracker();
};
__gaTracker.getByName = noopnullfn;
__gaTracker.getAll = function() {
return [];
};
__gaTracker.remove = noopfn;
window['__gaTracker'] = __gaTracker;
})();
}
Thanks for the additional information.
It looks like the dev implemented GA on your page with analytics.js, BUT changed the function from ga() to __gaTracker()
Also note, the 6th parameter for the event value should be an integer, it is optional and if it is 0, you don't need to include it.
Thus your function from jquery should be just renaming ga to __gaTracker:
(function($) {
/* For GA Event Tracking (Free Report CTA) */
$(".free-report").click(function() {
__gaTracker('send', 'event', 'Free Report', 'Claim Now', 'Free Report Claim', 0);
});
})( jQuery );
I made an unnoticeable mistake during the implementation. On the Analytics Dashboard, in my Goal Details, I have chosen the "value" as greater than 0. And as I have coded previously into my site, I am using 0 as the value in the script which makes the condition not able to met. So what I did is I changed the value as equal to 1 and changed the script's value as well into 1. #XTOTHEL gave me a great way to start with. First, since I am using MonsterInsight Plugin and as seen on the console, it is using the __gaTracker(''') rather than ga('''). So what I did is I changed this...
(function($) {
/* For GA Event Tracking (Free Report CTA) */
$(".free-report").click(function() {
ga('send', 'event', 'Free Report', 'Claim Now', 'Free Report Claim', '1');
});
})( jQuery );
...into something like this...
(function($) {
/* For GA Event Tracking (Free Report CTA) */
$(".free-report").click(function() {
__gaTracker('send', 'event', 'Free Report', 'Claim Now', 'Free Report Claim', '1');
});
})( jQuery );
And now, everything works as expected! Thanks #XTOTHEL!

google analytics not tracking custom dimension in context to events

I need to differentiate the users (Internal and External) who are performing some event action. so I am using the following code to track the user using custom dimension. My end goal is to know who performed the specific event by internal or external user
ga('send', 'event', 'Contract Change', 'click', 'Landing Page', 'My Value', {
'dimension3': 'External'
});
ga('send', 'event', 'Contract Change', 'click', 'Landing Page', 'My Value', {
'dimension3': 'Internal'
});
I have triggered this tracking code from javascript console for the testing purpose however it's not logging any data and I am not able to get the custom dimension value at any of the place.
I would change a couple of things:
Integers for event value: like Eike Pierstorff said, the event value has to be an integer. Technically you could leave the field out as it's optional, but it's best practice to assign values to your goal, so you can quantity the importance of user actions on your website:
https://developers.google.com/analytics/devguides/collection/analyticsjs/events#event_fields
Set dimensions before events: what you're doing should work, however it makes the code harder to read (most code formatting will break the {} syntax into 2 lines). Also, if you're sending multiple events which should be associated with the dimension, it's just cleaner to have the dimension declaration first, then all your events. Finally, if it's a user-scope dimension (internal vs. external users), it's more logical to declare the dimension before events, otherwise it looks like the dimension is hit-scope:
For instance:
ga('set', 'dimension3', 'Internal');
ga('send', 'event', 'Contract Change', 'click', 'Landing Page', 10);
ga('send', 'event', 'Other event with dimension', 'foo', 'bar', 20);

Event tracking in Google analytics is not displaying events data

I am adding Google Analytics code in my website, it displays active users but not but displaying the event list empty.
I tried both below codes
1)
jQuery('.btn-cart').click(function() {
ga('send', 'event', 'add-to-cart', 'add','product-added-to-cart');
});
2)
onclick("_gaq.push(['_trackEvent', 'whitepaper', 'add', 'product-added-to-cart']);")
Please let me know where i am doing wrong.
I found the solution.
jQuery('.btn-cart').on('click',function() {
_gaq.push(['_trackEvent', 'Add to Cart', 'Add To Cart Clickthrough', '<?php echo $currentUrl = Mage::helper('core/url')->getCurrentUrl();?>']);
});

Resources