Adding two Google Analytics accounts to one page

The contents of this article may be out of date. It has been archived and will no longer be updated, comments are closed and the page is provided for reference purposes only. You should now be using Universal Analytics not Classic Google Analytics as used in this article.

There are times when you would like to track your page visits using Google Analytics and also someone else wants to do the same. We have had this situation where the client wants to have the data in their analytics account and we also would like to track the site using our account. We have also had external SEO companies that want to track the site using their account.

I have found a number of posts, forum entries and blogs that give examples of how this is achieved. Some are longwinded and some just plain wrong. To add tracking for two accounts using the asynchronous code that is placed before the closing head tag google describes doing this in its usage guide. All I have done here is show the full code snippet.

<script type=“text/javascript”>
var _gaq = _gaq || [];
  _gaq.push(
  [‘_setAccount’, ‘UA-XXXXA-X’],
  [‘_trackPageview’],
  [‘b._setAccount’, ‘UA-XXXXB-X’],
  [‘b._trackPageview’]
);
(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>

You can just copy the above code and replace UA-XXXXA-X and UA-XXXXB-X with the two account codes that you want to use to track the site.

This article was posted on 6 May 2011 in Code, Google, Javascript, Snippets

comments

What you have had to say about all this...

how about subsequent numbers of accounts ? Use: [‘c._setAccount’, ‘UA-XXXXC-X’],
  [‘c._trackPageview’] and so forth ?

- Jan

Nice development. Will try this code.

- barristers

We have a CMS that adds the GA site wide (in the footer) however a supplier has provided GA for us to put on a single page and I only have the content area I can use to add this in the CMS. How do you advise adding the second tracking code?

- Stuart

That's the end of this article. I hope you found it useful. If you're enjoyed this article why don't you have a look around the archives, where you can find some more tutorials, tips and general ramblings.