Thursday, August 4, 2011

Track Image Search Traffic as Search Engine Hits with Google Analytics

The default behavior of Google Analytics is to treat inbound hits from Google Image Search as a referring site rather than a search engine.  In order to track Image Search traffic as an organic search engine hit, replace your GA script with the one below:
var _gaq = _gaq || [];
  _gaq.push([ '_setAccount ', 'UA-XXXXXXX-X ']);
      var ref = document.referrer;
      if (ref.search(/google\.([^\/]+)\/(ima?g|.*[?&]tbm=isch|.*[?&]site=images)/i) != -1) {
        var regex = /google\.([^\/]+)\/.*/i;
        var match = regex.exec(ref);
        _gaq.push([ '_addOrganic ', 'images.google ', 'q ',true]);
        if (ref.search(/[?&]prev=/i) != -1) {
          regex = /[?&]prev=([^&]*)/i;
          var match2 = regex.exec(ref);
          _gaq.push([ '_setReferrerOverride ',  'http://images.google. '+match[1]+unescape(match2[1])]);
        }
        else
        {
          _gaq.push([ '_setReferrerOverride ',  'http://images. '+match[0]]);
        }
      }
  _gaq.push([ '_trackPageview ']);
  (function() {
    var ga = document.createElement( 'script '); ga.type =  'text/javascript '; ga.async = true;
    ga.src =  'http://www.google-analytics.com/ga.js ';
    var s = document.getElementsByTagName( 'script ')[0]; s.parentNode.insertBefore(ga, s);
  })();
Just make sure to edit line 2 replacing UA-XXXXXXX-X with your own site id.

Now you should be able to track your image search hits by their keywords and have them counted as search engine traffic in Google Analytics.