How to Gtag Enhanced Ecommerce Woocommerce Analytics Tracking - Implementation Guide
Whether you want to understand your e-commerce traffic or connect it to Google Adwords, you will need to set up enhanced e-commerce analytics. Here’s everything you need to know, including code from my own implementation. I tried to keep it focused on the functions.php file so it’s easy for you to copy and paste. I am using the Storefront theme.
First of all, we need to be able to edit the functions.php file. For that, you will need to set up a child-theme. Functions.php file is designed to be edited, which allows you to add functionality without changing core files, which is first of all messy, and second of all would disappear after updating WordPress.
Important: Always backup all your files and database before playing with your WordPress!
Setting up the child theme
Skip this step if you have a child theme set up already. There are many guides on how to do this, so I will keep it brief. We are working with the default storefront theme.
- create a new directory in the wp-content/themes folder, and name it “storefront-child”
- create style.css and functions.php file inside the directory
- Inside the style.css file place the following code:
/*
Theme Name: Storefront Child
Theme URI: http://digit.st/
Description: Storefront Child Theme
Author: Mate Gvo
Author URI: http://digit.st
Template: storefront
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
Text Domain: storefrontchild
*/
4. Now go to your themes in /wp-admin and activate the child theme
5. Open the functions.php file and get ready for setting up Google Enhanced E-commerce tracking!
Enhanced e-commerce
Please make sure you have gTag installed on your website, if not follow a guide on creating a google analytics account and gTag installation:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-ABCDEFGH"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'AW-<your-code>');
</script>
A slight modification to the above — When I am working on any website or project I create a development environment on my computer, I don’t work on the server. My development website works under http://localhost:8000 address. I don’t want to send events from this address to gTag, so I am adding a filter:
<script>
if (window.location.host === 'localhost:8000') {
window.gtag = function (event, name, data) {
console.log({event, name, data})
}
} else {
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'AW-<your-code>');
}
</script>
Notice the if (window.location.host === ‘localhost:8000’) — when in a development environment, I am logging the gTag events to my javascript console, to be able to verify their content.
gTag Events
Enhanced eCommerce allows us to track the following events:
select_content
A click on a product or product link for one or more products.view_item
A view of product details.add_to_cart
Adding one or more products to a shopping cart.remove_from_cart
Remove one or more products from a shopping cart.begin_checkout
Initiating the checkout process for one or more products.set_checkout_option
Sending the option value for a given checkout step.refund
The sale of one or more products.view_refund
The refund of one or more products.view_promotion
We are going to set up most of these events.
I am not going to cover the select_content event, as I am using a separate system to display product lists because WordPress slow and clunky, and e-commerce conversions depend on speed. Therefore I integrated another system that works instantaneously, rather than trying to fix something that’s not working reliably. But this event is very simple to track and I hope that you can manage to add it yourself.
1. Tracking view_item and add_to_cart
add_action('woocommerce_after_main_content', 'trackItemView');
function trackItemView()
{
global $post;
$product = wc_get_product($post->ID);
?>
<script>
SingleItemEvent = {
"items": [
{
"id": "<?php echo $product->get_id() ?>",
"name": "<?php echo $product->get_title() ?>",
"category": <?php echo json_encode($product->get_category_ids()) ?>,
"quantity": 1,
"price": '<?php echo $product->get_price() ?>'
}
]
}
gtag('event', 'view_item', SingleItemEvent);
// track adding to cart
const cartBtn = document.querySelector('.single_add_to_cart_button')
cartBtn.type = "button"
addToCartFunc = async (e) => {
cartBtn.removeEventListener('click', addToCartFunc)
gtag('event', 'add_to_cart', SingleItemEvent);
setTimeout(() => {
cartBtn.type = 'submit'
cartBtn.click()
}, 100)
}
cartBtn.addEventListener('click', addToCartFunc)
</script>
<?php
}
2. Tracking cart steps: begin_checkout and checkout_progress events
// begin_checkout, checkout_progress
add_action('woocommerce_cart_totals_after_order_total', 'trackCartCheckout');
add_action('woocommerce_after_checkout_billing_form', 'trackCartCheckout');
function trackCartCheckout()
{
$items = WC()->cart->get_cart();
$itemsAnalyticsData = [];
foreach ($items as $cart_item_key => $cart_item) {
$_product = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key);
$item = [
"id" => $cart_item['product_id'],
"price" => intval($_product->get_price()),
"name" => $_product->get_name(),
"quantity" => $cart_item['quantity']
];
$itemsAnalyticsData[] = $item;
}
$itemsJson = json_encode($itemsAnalyticsData);
if (current_filter() === 'woocommerce_after_checkout_billing_form')
$event = 'checkout_progress';
else
$event = 'begin_checkout';
?>
<script type="text/javascript">
var cartItems = JSON.parse('<?php echo $itemsJson ?>');
var cartCoupons = JSON.parse('<?php echo json_encode(array_keys(WC()->cart->get_coupons())) ?>').toString()
var gtagEvent = {
"items": cartItems,
"coupon": cartCoupons
}
gtag('event', '<?php echo $event ?>', gtagEvent);
</script>
<?php
}
3. Tracking cart and checkout option settings
This code will send shipping and payment method selections to gTag.
// set_checkout_option
add_action('woocommerce_cart_totals_after_order_total', 'trackCheckoutOptions');
add_action('woocommerce_after_checkout_billing_form', 'trackCheckoutOptions');
function trackCheckoutOptions()
{
?>
<script type="text/javascript">
document.addEventListener('change', (e) => {
let event
const target = e.target;
if (target.classList.contains('shipping_method')) {
event = {
"checkout_option": "shipping method",
"value": target.value
}
} else if (target.name === 'payment_method') {
event = {
"checkout_option": "payment method",
"value": target.value
}
} else {
return false
}
gtag('event', 'set_checkout_option', event);
})
</script>
<?php
}
4. Tracking purchase event
add_action('woocommerce_thankyou', 'send_conversion_to_google_merchant', 1);
function send_conversion_to_google_merchant($order_id)
{
$order = wc_get_order($order_id);
$products = [];
foreach ($order->get_items() as $item_id => $item) {
$products[] = [
"id" => $item->get_product_id(),
"name" => $item->get_name(),
"category" => implode(',', $item->get_category_ids()),
"variant" => $item->get_variation_id(),
"price" => $item->get_total()
];
}
?>
<script>
purchaseGtagEvent = {
"transaction_id": "' . $order_id . '",
"value": Number.parseFloat("' . $order->get_total() . '"),
"currency": "' . $order->get_currency() . '",
"tax": Number.parseFloat("' . $order->get_total_tax() . '"),
"shipping": Number.parseFloat("' . $order->get_shipping_total() . '"),
"items": ' . json_encode($products) . '
}
gtag("event", "purchase", purchaseGtagEvent);
</script>';
<?php
}
5. Remove from cart
add_action('storefront_footer', 'trackCartRemoval');
function trackCartRemoval()
{
?>
<script>
if (document.querySelectorAll('a.remove')) {
document.querySelectorAll('a.remove').forEach((el) => {
el.addEventListener('click', (e) => {
gtag('event', 'remove_from_cart', {
"items": [
{
"id": el.getAttribute('data-product_id'),
}
]
});
})
})
}
</script>
<?php
}
6. Tracking promotions
If you have added in your template a promotional banner, it’s worth tracking impressions of the promotions with following script:
gtag('event', 'view_promotion', {
"promotions": [
{
"id": "<promotion-name>",
"name": "<promotion-name>"
}
]
});
See the demo of working set up:
Thank you
Please let me know in comments below, whether this article was helpful, or what wasn’t clear or can be improved, or leave some “claps” if you found this useful