Tracking multiple Google analytics profiles

On 18 Apr, 2012 in Javascript with Comments
Tracking multiple Google analytics profiles

Recently we wanted to add multiple tracking codes to a single analytics script to track both devw3.com and devw3.com/html.The problem is analytics data for both comes separately. To merge them we created another profile called devw3 complete.

Default analytics script:

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'XXXXXXXXXXX']);
  _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') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

Now replace

_gaq.push(['_setAccount', 'XXXXXXXXXXX']);
  _gaq.push(['_trackPageview']);

Where _setAccount value will be the tracking code and _trackPageview defines the process.

To add multiple tracking code we should merge the functions _gaq.push into a associative array as shown below

_gaq.push(
['_setAccount', ‘XXXXXXXX’],
['_trackPageview']
)

Now to add second tracking code append “b.” before _setAccount and _trackPageview in _gaq.push() as shown below

_gaq.push(
['_setAccount', ‘XXXXXXXX’],
['_trackPageview'],
['b._setAccount', 'XXXXXXX'],
['b._trackPageview']
)

Snippet for multiple tracking code:

<script type="text/javascript">
var _gaq = _gaq || [];
	_gaq.push(
	['_setAccount', ‘XXXXXXXX’],
	['_trackPageview'],
	['b._setAccount', 'XXXXXXX'],
	['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>
Note: To add more tracking codes follow same steps by replacing the prefix before _setAccount and _trackPageview with remaining alphabets (b to z – where default is ‘a’)

Hope you liked this article, don’t forget to comment

Tags: , , ,