Posted on

Magento and Google Analytics – Use ‘First Touch’ Tracking To See How Your Customers First Visit Your Store

At the recent Auckland Magento Meetup I had the privilege of seeing Mark Hammersley’s presentation on email marketing – Mark’s a fascinating guy and a real expert, I highly recommend checking out his site. One of the things that came up during his presentation was the idea of first touch tracking your visits, particularly in the sense that if they first come to you because of an email, and you build a relationship with them and they eventually buy from you – knowing if it was an email and which one brought them to the store in the first place is very valuable information.

Magento does not track this out of the box and neither does Google Analytics, however with a simple customization it can be added to the store. This blog post will run through how I added it to two of our new World Wide Access stores, <plug> Cariboo Cribs – which sells cribs and cots to the UK and soon to the USA – and Dominion New Zealand – which sells high quality sheepskin coats and boots (think New Zealand made Ugg).</plug>

There are basically 3 steps to implementing this Magento customization – none of them are particularly tricky, Let’s do them together now.

The Custom Javascript

This functionality requires some custom javascript be added to your pages. The original code was created and is maintained by Distilled. You can get the original version here and read the blog post about setting it up. None of this would be possible without their original work, so big thanks to them.

To use this functionality in Magento (at least Magento 1.4.X) we need to add support for the sort of new async Google Analytics code. To do this I added an extra function shown below to the bottom of the javascript file:

// Updated to work with the Google analytics Async code by Ashley (
// refer to distilledFirstTouch() for comments.
function asyncDistilledFirstTouch(asyncStack){
	try {
		if (distilledCheckAnalyticsCookie() === 0){
			asyncStack.push(['_setCustomVar', 1, "l", distilledTruncate(window.location.pathname), 1]);
			asyncStack.push(['_setCustomVar', 2, "s", distilledTruncate(, 1]);
			asyncStack.push(['_setCustomVar', 3, "r", distilledTruncate(document.referrer.substr(7,document.referrer.length)), 1]);
			asyncStack.push(['_setCustomVar', 4, "q", distilledTruncate(document.referrer.match(/(?:([#]|[?]|[&]))(?:(encquery|k|p|q|qs|qt|query|rdata|search_word|szukaj|terms|text|wd|words))=[^&]*/i)[0]), 1]);
	} catch (err) {}

The change is just to pass the async stack in to the function and use the push method to add the required _setCustomVar calls which then show in Analytics as Custom Variables. If you want my modified version, until the change (or a better one!) is applied to the project itself, you can download the whole custom javascript file.Update: Will has published the changes in the Google Code project, you can get them from there directly now. Thanks Will!

So now you should have the javascript file, let’s put it in to our Magento store and ensure it get’s included in the page HTML.

Add the Javascript to Magento

To add a piece of javascript to Magento pages we need to edit the page.xml file in your particular theme. So edit this file: app/design/frontend/YOUR_PACKAGE/YOUR_THEME/layout/page.xml, and add the following line of XML:

<action method="addItem"><type>skin_js</type><name>js/ga/distilled.FirstTouch.js</name></action>

Add the XMl to the end of the <block type="page/html_head" name="head" as="head"> section.

What that XML does is tells Magento when it is determining the layout for all pages to add the javascript js/ga/distilled.FirstTouch.js to your html head element. Great, now we need to actually add that javascript to the right place.

Copy the javascript code from the previous section to this directory (you will probably need to make the ga parent directory): skin/frontend/YOUR_PACKAGE/YOUR_THEME/js/ga/

If you use the command line (and you should), something like this will work from the root of your Magento store:

mkdir skin/frontend/YOUR_PACKAGE/YOUR_THEME/js/ga/
mv distilled.FirstTouch.js skin/frontend/YOUR_PACKAGE/YOUR_THEME/js/ga/

Modify the Core Analytics code

The last step is to make sure that our new custom code gets used by Magento when it renders the Google Analytics code. Don’t ask me why when they have a great templating engine at their disposal varien decided to put this code into a core Block file, but never-the-less we’ll need to override it in order to do what we want. Here’s the commands to do it on the command line:

# First, if the file already exists, be careful modifying it and don't overwrite it below!
ls app/code/local/Mage/GoogleAnalytics/Block/Ga.php 
mkdir -p app/code/local/Mage/GoogleAnalytics/Block/
cp app/code/core/Mage/GoogleAnalytics/Block/Ga.php app/code/local/Mage/GoogleAnalytics/Block/
vi app/code/local/Mage/GoogleAnalytics/Block/Ga.php # or use the editor of your choice

Note: Be careful not to override this if it already exists, for example I already had this fix in mine.

Edit the file app/code/local/Mage/GoogleAnalytics/Block/Ga.php and add this line at around line 182:


It should look like this:

    _gaq.push(["_setAccount", "' . $this->getAccount() . '"]);
    _gaq.push(["_trackPageview", "'.$this->getPageName().'"]);

Check it’s working

Right, now you can clear your Magento cache and check your handywork worked. You’re doing this in a test environment, right? So if you made a mistake, it won’t be a big problem for your visitors. To check it’s working look for 2 things in the source code of your Magento page (view source).

1) The asyncDistilledFirstTouch(_gaq); we added should now show up.

<script type="text/javascript">
    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
    // Fix from:
	var _gaq = _gaq || [];
    _gaq.push(["_setAccount", "UA-4134648-12"]);
    _gaq.push(["_trackPageview", "/magento/dominion/"]);

2) The javascript should be imported:

<script type="text/javascript" src=""></script>

Note: Your javascript console shouldn’t show any errors either – clear it and refresh the page to check.

Now what?

Give it a day or so and you should see your results coming through Google Analytics in the Visitors -> Custom Variables section. I am absolutely not an expert at Google Analytics reporting so I’m not sure the best way to actually report this data, if we’re really lucky someone might post a comment with some tips on that. All I did was make a custom report that shows source as the first level and then various custom variable values as second layers. This let’s you see the original source for other sources (and you could look at conversion rate of those visits too).

Also, if there is enough interest in this functionality, I’ll consider making it a free Magento extension too as even though the changes are simple, there’s a lot of fiddling around which might be easier if it can be avoided with an extension. So if you like the idea of doing this got put off by the thought of modifying PHP and XML files, then let me know.

Oh and as always, any feedback greatly appreciated!

14 thoughts on “Magento and Google Analytics – Use ‘First Touch’ Tracking To See How Your Customers First Visit Your Store

  1. Interesting, as always!

    When we send emails, we use this instead, no Mage hacking required:

    Then stick that URL in so they’re nice and short and give you a real-time tracking mechanism, satisfying that need-to-know-now desire. A day later, Google Analytics will show everything broken down not just by email campaign, or actual email, but depending how you use above tool, even by the actual link they clicked first.

    Lastly, if it’s a big mail-out, it’s very exciting to then launch Woopra ( and watch the traffic in real-time clicking through your site, putting stuff in the basket and checking out.

    As we often say in Europe, or Holland at least, many/all roads lead to Rome. There isn’t necessarily a right or wrong way to get there, but some are smoother, or more fancy, or quicker.

    Always nice to see how others get there!

    Last week we had a Mage Meet-up in London and there were people preparing for Magento shops taking a thousand orders a day. That’s certainly cool stuff to hear about.

  2. Hi, Thanks JT – I think that’s good for the specific email tracking right? Services like Mailchimp even take care of it for you (Mailchimp is great btw, they get my seal of approval!).

    What that means is the campaign info is already added to the URL’s in the email for you.

    What this functionality adds is that if the first visit to your site was from an email, then forever (till the cookie goes away) after you would have recorded that info. So if they later search your site name directly in google to come back to you on the 5th visit and buy, you’ll be able to look back and see that the _first_ time they came to you it was from your email, and you can give your email marketers a pat on the back and a banana break!

  3. Yes, I think you are right there in that as standard, my way wouldn’t be persistent. My GF works at one of the larger PPC companies and they use Searchware, Marin etc. to track clicks and they too do what you describe, recording where the very first touchdown originated from.

    To have that in Magento like you describe (for free) is very neat indeed.

    I’ll make sure I’m fully awake before I comment next time 🙂

    Re Mailchimp, for data related laws and regulations, I’m still waiting for a pure UK based service which is fully integrated with Magento. Until that day, we’ll use in-house tools like SogarCRM or Magento itself even. Setting up your own server MTA for maximum deliverability is a Royal PITA but once you know the 600 steps involved, it works quite nicely. The things us geeks have to suffer…

  4. I’ll register my vote of interest in this as an extension. I’m sure you can write it up on your train ride home like your others. 😉 But seriously, this would be great to have. If it doesn’t make its way into an extension, the steps above look pretty straightforward and I’m sure I’ll end up adding this into my sites down the road.

  5. vote registered! You may not have to wait for me though, I heard from Fooman that he might add this to his GA extension, so that’d be good eh. I’ll let you know if I hear any more.

  6. Hey Ash,

    Just trying this, can’t seem to get it to work…ie results not coming through to Visitors -> Custom Variables.

    I’ve given it more than a day since I made the changes. In view source I can see the js loading (in the Fooman mimify stuff) and, the correct line in the analytics code (modified the Fooman Ga.php).

    Anything else I should check?


  7. Hi, Graham – I just had a quick look at your source code – I think you’re using the older, non-async GA code. In that case, refer to the original article about how to add the distilled javascript call to your GA.php. Let me know how that goes.

  8. I’ll be very interested to see this extension too. Even if it’s integrated to Fooman extension, it will be great.

    We are using MailChimp too for one of our clients and it’s linked with their Google Analytics account, but it’s more like a complement as like you said Ashley, it’s also for a global report for individual report.

    Keep us posted about the extension!

  9. I don’t get anything in the User Defined or Custom Variables reports at all (or rather: I get “(not set)” for every visitor in the User Defined report, and “You have 0 unique custom variables” in the custom variables report). Here’s my code (I should be clear: I’m not using Magento):

    <script type="text/javascript" src=""></script> <script type="text/javascript">    var _gaq = _gaq || [];  _gaq.push(['_setAccount', 'UA-XXXXXXX-1']);  _gaq.push(['_setDomainName', 'none']);  _gaq.push(['_setAllowLinker', true]);  asyncDistilledFirstTouch(_gaq);  _gaq.push(['_trackPageview']);   (function() {    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);  })(); </script> 

    Is this correct usage? There are no JS errors and I can debug it line by line in Firebug.

  10. Just to let you know – the results have just started coming through. It took five days in total to appear and you can’t see yesterday’s results… but prior to that they exist.

  11. Thanks for stopping back in Dan – I think my data took about a day to start coming through, so hopefully you’re just experiencing some intermittent slowness with the analytics data.

  12. This “first touch” tracking is a great idea !
    I just installed the Fooman extension. Should I do some other operation manually (maybe add the code in page.xml…) or everything is now in the Fooman extensio ?

  13. I’m in the same case as So What. Have I to do something manually after the install of Fooman extension ?

  14. Hello all.

    I have a spinning head….i can not solve a problem.

    We have put UA-code in Magento and it is seeable on frontend.
    BUT….at some pc’s it is not shown in source????
    Why??? People are on SAME IP. I do not know why Magento somethimes shows UA-code and sometimes not. We have problems with our reporst in Analytics now…

    Please help me out….Thanks!

Comments are closed.