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 Measure & Optimize, 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 -->

        [...]

Adding the Google Tag Manager Snippet to your Magento Installation

Here’s a way to update your Magento install in order to make the GTM pop right in place. Simply make your way to this file and make it look exactly the same as this and save. Beware that this will remove any classic Google Analytics tag that would’ve been present.

gtm magento ga phtml screenshot A Guide To E Commerce Conversion Tracking Using Google Tag Manager

Once it’s done, make your way in the Magento Admin Backend to System -> Configuration -> Sales -> Google API and expand the Google Analytics section. Make sure to Enable the feature and add your Google Tag Manager container ID to the Account Number field. Hit save and you should have your GTM tag up and running on all your pages.

google analytics magento admin panel A Guide To E Commerce Conversion Tracking Using Google Tag Manager

Make sure to do the other steps below BEFORE making this change. Otherwise, this change will result in Google Analytics data loss during the process.

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
I'm currently an SEO, PPC and Analytics specialist here at Ludis Media! 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!

25 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'
      }]
      }];

  6. Pieter says : Reply

    Hi,

    I have a question about the example you and others use.

    In the example the transaction total is 11.99. But the order consist of three products with the total transaction price of 31.97.

    ‘price’: 11.99,
    ‘quantity’: 1

    ‘price’: 9.99,
    ‘quantity’: 2

    Is the variable “transactionTotal” getting the wrong value ? Should it be:

    ‘transactionTotal’: 31.97,

  7. Steve says : Reply

    Hi Pier,

    A very good and interesting read. We are looking to implement GTM on our eCommerce site which is on megento. Before we simply put the GA tracking code in megento and it did all the rest. What is worrying us is the Data Layer, but reading above most people are too. I have found a plug in http://www.magentocommerce.com/magento-connect/google-tag-manager-3.html. Not sure if you have seen this one, but wondered if you think this good solution to a tricky problem?

    • Hi Steve,

      The plugin you proposed seems like a solution that wasn’t available at the moment I wrote this. I would try it if I were you. Keep in mind that this plugin is not compatible with magento 1.8 as we write those lines, meaning you could have problems using it with a Magento 1.8 install.

  8. Marcelo says : Reply

    Hi Pier,

    Good article. Do you know how would the data layer output look like with the new Universal Analytics e-commerce tracking?

    Thanks!

    • Hi Marcelo, this is an interesting question. The truth is, using Universal Analytics or not, the dataLayer is sort of “future proof”. What I mean by that is that, the dataLayer speaks to the Google Tag Manager, not Google Analytics, ensuring that the GTM will do it’s magic and adapt your data to whatever is needed in order for the tracking to work.

      That being said, the only thing that should change in the procedure is to choose “Universal Analytics” instead of the “Classic version” in the tag type dropdown.

      We all know that the Google’s seemless isn’t always as seemless as we would’ve thought in the first place so make sure to validate your data after this massive change, even though everything should go just right. Take note that Google seems to already have thought about this and gives you the chance to come back to an earlier version of your containers, just in case things do work as planned.

  9. Hi Pier-Yves,

    Would another path be to implement the Magento PHP code directly in a macro inside GTM? (create an html object with the PHP values and the dataLayer population)

    In that case, you would be totally independant from the Magento files (except the part where you have to change the standard _gaq.push).

    • Hi Marc-André,

      Sure, you could do some sort of black magic macros in GTM in order to fetch your conversion values directly from HTML tags that you would have on your Thank You page without sending any dataLayer object to the GTM, but that’s a way more advanced technique.

      I’m glad you point it out as it will be the subject to an entirely new how-to article soon!

  10. Eric says : Reply

    In all of the blog posts I’ve come across, the embed code contains sample values, such as:

    ‘transactionId’: ’1234′,
    ‘transactionAffiliation’: ‘Acme Clothing’,
    ‘transactionTotal’: 11.99,

    I’m working on a music site with 6 albums and ~60 individual songs for sale. Is there a way to dynamically populate these values with what was in the user’s shopping cart? I suspect there is, I just can’t find it.

    Thanks! Great blog – very valuable.

    • Hi Eric! Are you using Magento? If so, this blog post will help you with every steps. Otherwise, you should be able to retrieve this info from your eCommerce platform by adapting the PHP script section with the help of a programmer. There is also a way to do so with advanced macros directly in GTM. Stay tuned, as I will publish an article on that somewhere next week! Thanks.

  11. Mike says : Reply

    Hi Pier!

    Very nice tutorial. One question though: In the first step “Setting up Google Tag Manager”, it says “put the Google Tag Manager snippet right after the opening of the tag” (as is anyway recommended by Google).

    I’m wondering though how this can be correctly set-up in Magento? Via backend “System – Configuration – Design”, snippets can only be added either at the END of head or END of body – but not after the opening body.

    Any recommendations?

    • Hi Mike, that’s indeed a good question.

      In order for this to work, you will need to have your theme modified. You can either modify your header directly through your theme or adapt the Google Analytics module to do so. I prefer the second option. Please have a look at this section of the article, you’ll have the steps towards doing this.

      Thanks!

      • Mike says : Reply

        Hi Pier!

        Thanks for the quick response. Okay, now I see – when following/reading the tutorial, I didn’t make the connex from you mentioning “it should be added at the beginning of the body”, to your actual description “Adding the Google Tag Manager Snippet to your Magento Installation” of how to do so.

        I gave this a try now – however, I didn’t have the ga.phtml file in my template directory, therefore I copied it from the base template. After modifying as described above, it is still injecting the wrong code though (still injecting a GA snippet instead of the GTM snippet – seems it doesn’t use my newly created ga.phtml).
        In case u have any ideas on that, happy to hear your feedback.

        Thanks anyways,
        Mike

        • Hi Mike,

          Do you have any sort of cache enabled? Maybe that’s why it doesn’t trigger. Otherwise, try to modify the base version directly as it might work!

          Thanks.

          • Mike says :

            Hi Pier,

            tried that already before, didn’t work either though.
            Nothingtheless, if I only activate Google Analytics in Backend (as in your screenshot above), I would assume it shld also be placed right at the beginning of , no? In my case, it is also still embedded somewhere withing head section (therefore, changing the snippet to include GTM instead of GA wld not pop up in the right place anyway, would it?)

            If it wasn’t just me, maybe it wld make the article even clearer if you were to clarify that “Here’s a way to update your Magento install in order to make the GTM pop right in place.” refers to “right place (:= beginning of body section).

Leave a Reply

TOP