Google Analytics Custom Variable Tracking Code Using The _gaq Global Object

Google Analytics Custom Variable Tracking Code
Google Analytics

This evening I was experimenting with adding custom variables to my Google Analytics tracking code, but when I checked Google’s custom variable documentation, it didn’t match the analytics code that I had.

Google Analytics changes their code for you to copy and paste quite often, seemingly every time I setup a new site to track.

The latest version of the analytics code that I was given used a new format, notably:

var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'youridhere']);
 _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);
 })();

The docs say to put the _setCustomVar code in before pageTracker._trackPageview() … but I no longer have that older style setup.

After a bit of digging around, I came up with a solution from documentation on the _gaq Global Object. The _setCustomVar code can be added as follows:

_gaq.push(['_setCustomVar', index, name, value, opt_scope]);

Just put this after the last push line up top and you’re good to go.

Hopefully Google Analytics will update their docs to reflect the newer code style using _gaq, but in the mean time, this is working for me.