Recently, I needed to dynamically set a Custom Variable in Google Analytics. This isn’t hard if you’re putting in the web tracking code by hand, but it can be a bit tough working with a plugin.
Yoast’s Google Analytics for WordPress plugin (which I highly recommend) can do this, although it’s not entirely intuitive.
First, you need to throw some Javascript into your to set a global variable. You can set whatever you want here, but make sure it’s got a priority of 1 when you add it to
wp_head
. That’s the only way to set it before the analytics code gets echoed. Add this to your functions.php
file or your own plugin:
function set_your_customvar() { echo " "; } add_action( 'wp_head', 'set_your_customvar', 1 );
Obviously, you’ll set your variable to whatever dynamic value you need it to be. In my case, I pulled the value from an existing cookie.
Then, you need to set your custom variable in the analytics code. To do this, go to Settings > Google Analytics in the admin area. Make sure ‘Show advanced settings’ is checked:
Then, scroll down to the ‘Custom Code’ area. Here, set the custom variable and pull in your global variable from before. Make sure you set the parameters properly. Also, make sure you use single quotes and not double, due to the way the plugin will strip some things out. For instance:
_gaq.push(['_setCustomVar',5,'my_custom_var',yourcustomvar,2]);
That’s it! Wait an indiscriminate amount of time (something like 2-24 hours), then log into Google Analytics. Look under Audience > Custom > Custom Variables, and set the ‘Primary Dimension’ to whatever slot you put your variable in.
If you just made the change today, make sure you update the date range Google Analytics is showing to include today. 🙂