Adding Social Interaction Analytics to Drupal’s Google Analytics Module

track by Celeste

If, like me, you read the recent announcement that Google Analytics just added social tracking to their tool, you’ll probably be thinking, “Nice, I’d like to get me some of that social media analytics”.

If you’ve checked the new fancy-schmancy version of the tool – look for the red New Version link in the top right-hand corner of the interface – it’s likely you’ll head straight for the Social section. Unless you’re getting lots of Google +1’s on your content, most of your traffic will be listed as Not Socially Engaged.

It’s a little disheartening, and probably not entirely true. The reason? You need some custom code in order to track Twitter and Facebook interactions. Fortunately, there’s documentation to help with this.

If you’re in a rush, I’ve glued together the bits of Javascript you’ll need to track Twitter and Facebook interactions:

function trackFacebook() {
  try {
    if (FB && FB.Event && FB.Event.subscribe) {
      FB.Event.subscribe('edge.create', function(targetUrl) {
        _gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
      });
      FB.Event.subscribe('edge.remove', function(targetUrl) {
        _gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]);
      });
      FB.Event.subscribe('message.send', function(targetUrl) {
        _gaq.push(['_trackSocial', 'facebook', 'send', targetUrl]);
      });
    }
  }
  catch(e) {
  }
}
function trackTwitter() {
  try {
    if (twttr && twttr.events && twttr.events.bind) {
      twttr.events.bind('tweet', function(event) {
        if (event) {
          var targetUrl;
          if (event.target && event.target.nodeName == 'IFRAME') {
            targetUrl = extractParamFromUri(event.target.src, 'url');
          }
          _gaq.push(['_trackSocial', 'twitter', 'tweet', targetUrl]);
        }
      });
    }
  }
  catch(e) {
  }
}
function extractParamFromUri(uri, paramName) {
  if (!uri) {
    return;
  }
  var uri = uri.split('#')[0];  // Remove anchor.
  var parts = uri.split('?');  // Check for query params.
  if (parts.length == 1) {
    return;
  }
  var query = decodeURI(parts[1]);

  // Find url param.
  paramName += '=';
  var params = query.split('&');
  for (var i = 0, param; param = params[i]; ++i) {
    if (param.indexOf(paramName) === 0) {
      return unescape(param.split('=')[1]);
    }
  }
}
trackFacebook();
trackTwitter();

These should work for any site using Google Analytics – you’ll just need to pop the code in between the code that calls the Google Analytics tracker. So in a standard implementation, it’d look something like this:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'XXXXXX']);

// STICK YOUR SOCIAL TRACKING CODE IN HERE
_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); })(); </script>

If you’re running a Drupal site and have the rather nifty Google Analytics module installed, it’s even easier to install the code (we’re running Drupal 6, but instructions should be very similar for other versions).

Login as an admin and navigate to admin > settings > googleanalytics and scroll down the page and expand the Advanced settings list, then do the same for the label Custom Javascript code.

Then copy/paste the social tracking code above (or grab from this plain text version) and insert into the field labelled, Code snippet (before). Click Save. You’re done. Grab a coffee, you deserve it.

N.B. This was put together very quickly with minimal testing, so make sure you test thoroughly. Any tips, problems, etc, feel free to leave a comment. This code has minimal error checking, if Twitter or Facebook’s Javascript isn’t present in the page, it should behave, but no guarantees. Use at your own risk.

Photo (cc) Celeste.

About 

Inquisitive. Hopeful. Jovial. Cantankerous. Digital marketer. Event organiser. Long-time fan of tech, collaboration and innovation. Exploring digital, social, business, technology, society, psychology & startups. Founder Chinwag, Digital Mission, Pitch NYC, ChinwagPsych. Former Exec Dir, Social Media Week London. More short stuff @toodlepip on Twitter.

  • facebook
  • flickr
  • googleplus
  • linkedin
  • twitter