nxt's place

Tag: analytics

Tracking organic ranking with google analytics

by on Oct.11, 2010, under Other

If you want to track your rank in the organic search results you can do the following:
First we need to check the referrer and see if it contains the necessary bits.

1
2
3
4
var rank= /^(?:http|https)\:\/\/(?:.+\.)*google\..+(?:\?|\&)cd\=(\d+)/.exec(document.referrer || '');
if(match) {
  alert('position = ' + rank[1]);
}

The next thing we want to do is modify our analytics tracker code to include a custom variable:

1
2
3
4
5
6
7
var rank= /^(?:http|https)\:\/\/(?:.+\.)*google\..+(?:\?|\&)cd\=(\d+)/.exec(document.referrer || '');
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-X']);
if(rank) {
  _gaq.push(['_setCustomVar',1,'Google_Ranking',rank[1],2]);
}
_gaq.push(['_trackPageview']);

We’ve set the custom variable to slot 1, and the last number two means that we scope it to the session.

Finally you’ll want to wrap it up in a closure to prevent polluting the global scope:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var _gaq = _gaq || [];
(function() {
  var rank= /^(?:http|https)\:\/\/(?:.+\.)*google\..+(?:\?|\&)cd\=(\d+)/.exec(document.referrer || '');
  _gaq.push(['_setAccount', 'UA-XXXXXX-X']);
  if(rank) {
    _gaq.push(['_setCustomVar',1,'Google_Ranking',rank[1],2]);
  }
  _gaq.push(['_trackPageview']);
 
  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);
})();

You can view your new statistics using the Advanced segmentation feature of Google analytics, but keep in mind that it’s only possible to harvest data from the links that are clicked on.

Comments Off on Tracking organic ranking with google analytics :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...