Integrate your module with Google Analytics

Last modified: August 7, 2008 - 19:35

This page is made for module developers.

The code example should help you to integrate your module with Google Analytics module. You should also see Advanced Google Analytics JavaScript Snippets about links to the Google Tracking API documentation.

<?php
function mymodule_preprocess_page(&$variables) {

 
// Example code. Make sure your module runs all values through drupal_to_js() to be protected against XSS.
 
$before = 'pageTracker._setDomainName(".example.com");';

 
$after  = 'pageTracker._addTrans("1234", "My Partner Store", "84.99", "7.66", "15.99", "Boston", "MA", "USA");';
 
$after .= 'pageTracker._addItem("343212", "DD4444", "Lava Lamp", "Decor", "34.99", "1");';
 
$after .= 'pageTracker._trackTrans();';

 
$variables['closure'] = preg_replace('/(.*)(<script type="text\/javascript">var pageTracker = _gat._getTracker\("(UA-\d{4,}-\d+)"\);)(.*)(pageTracker._trackPageview\((.*)?\);)(.*)(<\/?script>)(.*)/i', "$2$before$4$5$7$after$8", $variables['closure']);

}
?>

a much cleaner way to do it

danithaca - April 24, 2009 - 16:13

Damien (DamZ) proposed a much cleaner way of doing it:

<?php
// use hook_preprocess_page or hook_init, etc.
function mymodule_block() {
 
$node = menu_get_object();
 
$your_ga_code = "pageTracker._trackEvent('Click', '${node->nid}')";
 
$GLOBALS['conf']['googleanalytics_codesnippet_after'] .= $your_ga_code;
}
?>

The trick is that $GLOBALS['conf'] got flushed for every page request. so you can just use .= to append your GA code. To prepend your GA code, just use $GLOBALS['conf']['googleanalytics_codesnippet_before']

I've tested the code, and it works!! Thanks Damien!

Incorrect

hass - May 20, 2009 - 13:12

I'm not sure what the intention of this snippet was, but it cause double tracking. Do not use it!

 
 

Drupal is a registered trademark of Dries Buytaert.