A Guide To E-Commerce Conversion Tracking Using Google Tag Manager

A Guide To E-Commerce Conversion Tracking Using Google Tag Manager

by / Monday, 27 January 2014 / Published in PPC & Advertising

So, I came up with this fantastic idea to setup the script management of one of the clients I manage with Google Tag Manager, which is quite a fantastic idea for normal tags like Google Analytics, Remarketing tags and so on.

But then came the fun part: Conversion tracking with the GTM isn’t exactly what I expected; what I thought was Plug & Play came out to be just not compatible. The original Google Analytics e-Commerce tracking snippet doesn’t seem to speak the magical language of the Google Tag Manager wizard, which disappointed me quite a bit. Needless to say I went on a fantastic journey trying to decode the oh-so-simple-and-elaborate Google documentation relating to e-Commerce tracking with the Google Tag Manager. After achieving what was told to me like impossible by some of my peers, I thought I would setup a guide to e-Commerce Tracking using Google Tag Manager just in case someone else would be looking to go the same route.

If you are not familiar with what the Google Tag Manager is all about, it’s pretty simple. The Google Tag Manager is a snippet manager where you can manage where and when you show these snippets on pages using triggers. Sounds fun? Read on.

DISCLAIMER: Although these steps have proven to give good results for my clients, everything presented here must be seen as a proof of concept and may harm your Magento installation if things go wrong in some way. Therefore, the author, Pier-Yves C Valade, and Ludis Media discharge themselves from anything that could happen to any website by following the steps described in this article. The employment of a Magento specialist is highly recommended.

Setting Up The Google Tag Manager Account

If you don’t already have your Google Tag Manager account setup and ready, go on and create one. I recommend you take a look at this step-by-step guide from Big Daylight so that you can setup everything properly.

Make sure to put the Google Tag Manager snippet right after the opening of the <body> tag so that everything works as it is supposed to. Here’s what it looks like once on your page:

<html>
    <head>
        [...]
    </head>
    <body>
        <!-- Google Tag Manager -->
        <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXX"
        height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
        <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','GTM-XXXXX');</script>
        <!-- End Google Tag Manager -->

        [...]

Creating The Google Analytics Conversion Tag

Once you have your Google Analytics tag setup in GTM, what you will want to do is create another Google Analytics tag, made for transaction tracking this time, that will be able to see the data we will be serving it. Make sure to set the track type to “Transaction” instead of “Page View”!

google tag manager transactions configuration A Guide To E Commerce Conversion Tracking Using Google Tag Manager

Once this tag is setup, we will need to trigger it on the right thank you page.

Triggering The Google Analytics Conversion Tag

Triggering the tag we just created is quite easy, just click on the right on the button to add a triggering rule.

google tag manager trigger button A Guide To E Commerce Conversion Tracking Using Google Tag Manager

Once you get to the popup, the next step is to name the rule to something like “Transaction Thank You Page” and make it trigger only on the url containing the exact path to your thank you page, let’s say “/checkout/success”. Make sure to also add an event listener to “gtm.dom”, a built-in event that triggers once the page is fully loaded, so that you also fetch everything coming after the Google Tag Manager’s script.

google tag manager triggering rule popup A Guide To E Commerce Conversion Tracking Using Google Tag Manager

Then, save both the rule and the tag and publish your container.

Adding The dataLayer Object Magic To The Thank You Page

Now, you should have everything properly setup on the Google Tag Manager’s side. It is time to compute the transaction data and serve it to your freshly made tag.

Maybe you are already familiar to the _gaq object and the _trackTrans method which is the old method of when you weren’t using Google Tag Manager. It looks quite the same but it is named dataLayer instead of _gaq. You can also use the datalayer.push() method with it, but that’s another topic.

There’s many ways to fill and use the dataLayer object but here’s what mine looks like with the required variables filled in and how I managed to get to it with the Magento backend.

The Magento PHP code underneath

File: /app/code/local/Mage/GoogleAnalytics/Block/Ga.php
<?php
    protected function _getOrdersTrackingCode(){
        $orderIds = $this->getOrderIds();
        if (empty($orderIds) || !is_array($orderIds)) {
            return;
        }
        $collection = Mage::getResourceModel('sales/order_collection')
            ->addFieldToFilter('entity_id', array('in' => $orderIds))
        ;

        $aOrders = array();
        foreach ($collection as $order) {
            $objOrder = new stdClass();
            $objOrder->transactionId = $order->getIncrementId();
            $objOrder->transactionAffiliation = Mage::app()->getStore()->getFrontendName();
            $objOrder->transactionTotal = $order->getBaseGrandTotal();
            $objOrder->transactionTax = $order->getBaseTaxAmount();
            $objOrder->transactionShipping = $order->getBaseShippingAmount();

            $aItems = array();
            foreach ($order->getAllVisibleItems() as $item) {
                $objItem = array();
                $objItem['sku'] = $item->getSku();
                $objItem['name'] = $item->getName();
                $objItem['category'] = null; //todo
                $objItem['price'] = $item->getBasePrice();
                $objItem['quantity'] = $item->getQtyOrdered();
                $aItems[] = (object) $objItem;
            }

            $objOrder->transactionProducts = $aItems;
            $aOrders[] = $objOrder;
        }

        return (empty($aOrders))? null : sprintf('dataLayer = %s;', json_encode($aOrders));
    }
?>

The HTML page dataLayer output

<script>
    dataLayer = [{
        'transactionId': '1234',
        'transactionAffiliation': 'Acme Clothing',
        'transactionTotal': 11.99,
        'transactionTax': 1.29,
        'transactionShipping': 5,
        'transactionProducts': [{
            'sku': 'DD44',
            'name': 'T-Shirt',
            'category': 'Apparel',
            'price': 11.99,
            'quantity': 1
        },{
            'sku': 'AA1243544',
            'name': 'Socks',
            'category': 'Apparel',
            'price': 9.99,
            'quantity': 2
        }]
    }];
</script>

Allowing some time to testing

Once you manage to setup everything right, the next thing you will need to do is test things up! The last thing you would like to do is stop tracking data in you Google Analytics eCommerce profile. So, go on and make a test purchase or wait until you have some purchases you know you can check if they got through the whole process. If everything works as planned, you should have data flowing through in the next 24 hours.

ecommerce tracking google analytics dashboard A Guide To E Commerce Conversion Tracking Using Google Tag Manager

So, it’s as simple as that! Now, go on and enjoy the magic of the dataLayer!

The following two tabs change content below.
 A Guide To E Commerce Conversion Tracking Using Google Tag Manager
Always looking for new challenges, I am a leader who’s not afraid of anything! I am in constant improvement in all facets of my life and aims at every moment to excel. I am an excellent communicator and also have an open mind. On a more personal side, I am fond of scotch, cars, bikes and great food!

10 Responses to “A Guide To E-Commerce Conversion Tracking Using Google Tag Manager”

  1. Sam says : Reply

    How can I just implement this in success.phtml without using a function?

    • Hi Sam,

      There’s no actual way of doing this without altering the _getOrdersTrackingCode() function.

      You might want to get help from a specialist in order to make everything work as described.

      Hope this helps!

  2. Dan Brown says : Reply

    Hi, is there a way to grab this function for quick use in success.phtml? I just need to have PHP output that datalayer script.

    Thanks in advance!!

    • Hi Dan,

      By default, Magento will use the Google Analytics block which will output the _trackTrans code. You need to override the function to output the dataLayer instead of the default gaq.push() by copying the file from “/app/code/core/Mage/GoogleAnalytics/Block/Ga.php” to “/app/code/local/Mage/GoogleAnalytics/Block/Ga.php” and replacing the default _getOrdersTrackingCode() function for the one supplied in the article.

      You will then need to do a test purchase and look into the code if everything works okay for you.

      And remember, I am not responsible for any trouble you may get by playing around applying this. If you’re not comfortable editing code, please make it done by a specialist.

      Hope this helps!

  3. Lakinzn says : Reply

    Hi, pls re the data layer, do you implement it by yourself or is it up to a programmer to implement that on the page? And are you specifying it to him? Thx.

    • Hi, it is best suited to implement this with the help of a Magento programmer in order so that you do not break anything. I guess that a Magento programmer will understand what to do by reading this article without any major problem! Hope this helps.

  4. Sam says : Reply

    Thanks for the feedback. I skipped right to localizing the file and replacing the function to see what gets output on the success page, though I don’t get anything. I have Google API set to enabled.

    Do I need to go through the google tag manager steps in order for there to be any output on the success page?

    • Hi Sam,

      Prior to doing the change, did the function returned the conversion gaq.push()? If not, the problem is not in the function, but in your config! You need to have your built-in Google Analytics integration activated in Magento.

      Hope it helps!

  5. Yvan Nguyen says : Reply

    Hi, i’m using the following code as Anlytics ecommerce code in GTM:

    dataLayer = [{
    'transactionId': '3211',
    'transactionTotal': '1',
    'transactionProducts': [{

    'name': 'Fotovoltaico',

    'sku': 'Bolzano/Bozen',

    'category': 'Trentino Alto Adige',
    'price': '1',
    'quantity': '1'
    },{

    'name': 'Riscaldamento Ecologico',
    'sku': 'Bolzano/Bozen',
    'category': 'Trentino Alto Adige',
    'price': '1',
    'quantity': '1'

    },{

    'name': 'Solare Termico',

    'sku': 'Bolzano/Bozen',
    'category': 'Trentino Alto Adige',
    'price': '1',
    'quantity': '1'
    },{

    'name': 'Geotermico',
    'sku': 'Bolzano/Bozen',
    'category': 'Trentino Alto Adige',
    'price': '1',
    'quantity': '1'

    },{

    'name': 'Infissi',
    'sku': 'Bolzano/Bozen',
    'category': 'Trentino Alto Adige',
    'price': '1',
    'quantity': '1'

    }]

    }];

    This code is working only for a single product suche as “Infissi”, but it doesn’t work with the selection of 5 products. Which is the problem?
    Thanks

    • Hi,

      From what I see, all your SKUs are the same, which Google might see all of your 5 items like the same one and taking the last values you supplied, hence “Infissi”.

      A SKU is usually a unique and alphanumeric code that refers to a unique item. You should avoid using slashes or other non-alphanumeric symbols for compatibility purposes.

      Your datalayer object with unique SKUs could look something like this, but it’s up to you to define unique SKUs for each and every product you sell.

      dataLayer = [{
      'transactionId': '3211',
      'transactionTotal': '1',
      'transactionProducts':
      [{
      'name': 'Fotovoltaico',
      'sku': 'TAA-BB-Fotovoltaico',
      'category': 'Trentino Alto Adige',
      'price': '1',
      'quantity': '1'
      },{
      'name': 'Riscaldamento Ecologico',
      'sku': 'TAA-BB-Riscaldamento-Eco',
      'category': 'Trentino Alto Adige',
      'price': '1',
      'quantity': '1'
      },{
      'name': 'Solare Termico',
      'sku': 'TAA-BB-Solare-Termico',
      'category': 'Trentino Alto Adige',
      'price': '1',
      'quantity': '1'
      },{
      'name': 'Geotermico',
      'sku': 'TAA-BB-Geotermico',
      'category': 'Trentino Alto Adige',
      'price': '1',
      'quantity': '1'
      },{
      'name': 'Infissi',
      'sku': 'TAA-BB-Infissi',
      'category': 'Trentino Alto Adige',
      'price': '1',
      'quantity': '1'
      }]
      }];

Leave a Reply

TOP