Skip to content

Instantly share code, notes, and snippets.

@AndreasStokholm
Created October 26, 2011 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreasStokholm/1317894 to your computer and use it in GitHub Desktop.
Save AndreasStokholm/1317894 to your computer and use it in GitHub Desktop.
Add a custom variable to your google analytics data with the rank of the result leading into your page.
if (document.referrer != undefined) {
var rank = 0;
var array = document.referrer.split('&');
for (value in array) {
if (array[value].indexOf('cd') != -1) {
rank = array[value].replace('cd=', '');
}
}
if (rank > 0) {
_gaq.push([
'_setCustomVar', 2, // This custom var is set to slot #2
'Google_Ranking', // Variable name
rank, // Value to register
2 // Sets the scope to page-level.
]);
}
}
/**
*
* Usage example
*
**/
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'GOOGLE_ANALYTICS_SITE_IDENTIFIER']);
_gaq.push(['_trackPageview']);
if (document.referrer != undefined) {
var rank = 0;
var array = document.referrer.split('&');
for (value in array) {
if (array[value].indexOf('cd') != -1) {
rank = array[value].replace('cd=', '');
}
}
if (rank > 0) {
_gaq.push([
'_setCustomVar', 2, // This custom var is set to slot #2
'Google_Ranking', // Variable name
rank, // Value to register
2 // Sets the scope to page-level.
]);
}
}
(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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment