Tracking Social Interaction with GA in Drupal 7

Marko RosicWeb DevelopmentLeave a Comment

Couple of days ago Google added Social Interaction Tracking that gives you an option to track +1, Facebook and Twitter button engagement.

I’ve spent some hours to get this working and test, and here’s the solution that worked for me. I assume you’re using Google Analytics module.

Step 1

Download ga_social_tracking.js from Google and copy the file to scripts folder within your template directory.

Step 2

Open your template.php and copy the following code

// Header scripts

drupal_add_js('https://apis.google.com/js/plusone.js',
array('type' => 'external', 'scope' => 'header', 'weight' => 1)
);

drupal_add_js( drupal_get_path('theme', 'green_carbon') .'/scripts/ga_social_tracking.js',
array('type' => 'file', 'scope' => 'header', 'weight' => 2)
);

drupal_add_js('

(function(){
var twitterWidgets = document.createElement(\'script\');
twitterWidgets.type = \'text/javascript\';
twitterWidgets.async = true;
twitterWidgets.src = \'http://platform.twitter.com/widgets.js\';

// Setup a callback to track once the script loads.
twitterWidgets.onload = _ga.trackTwitter;

document.getElementsByTagName(\'head\')[0].appendChild(twitterWidgets);
})();

',
array('type' => 'inline', 'scope' => 'header', 'weight' => 3)
);

// Footer scripts

drupal_add_js('http://connect.facebook.net/en_US/all.js',
array('type' => 'external', 'scope' => 'footer', 'weight' => 1)
);

drupal_add_js('

(function() {
var e = document.createElement(\'script\'); e.async = true;
e.src = document.location.protocol +
\'//connect.facebook.net/en_US/all.js\';
document.getElementById(\'fb-root\').appendChild(e);
}());

window.fbAsyncInit = function() {
FB.init({appId: \'YOURAPPID\', status: true, cookie: true,
xfbml: true});

_ga.trackFacebook();
};

',
array('type' => 'inline', 'scope' => 'footer', 'weight' => 2)
);

This code calls all the needed scripts and loads Facebook and Twitter asynchronously and calls GA tracking functions. If you already have social buttons on your site you may skip the part below.

Step 3

Copy the html.tpl.php from /modules/system to templates directory inside your template and add <div id=”fb-root”></div>

<!--?php print $page; ?-->
<div id="fb-root"></div>
<!--?php print $page_bottom; ?-->

Step 4

Add the buttons to your node.tpl.php

<!--?php $curr_uri = url(('node/'.$node--->nid), array('absolute' => TRUE)); ?>

<a class="twitter-share-button" href="http://twitter.com/share" data-count="horizontal" data-url="<?php print $curr_uri; ?>" data-counturl="<?php print $curr_uri; ?>">Tweet</a></pre>
<div class="g-plusone" data-size="medium" data-count="true"></div>
<pre>

References

Customize this code as needed, and refer to these official pages for guidance

Share

Previous Article
Next Article