Drupal 7: How to use Google analytics custom variables in Drupal

Fri, 01/04/2013 - 11:34 -- Bruno Goossens

This article describes how I use the power of Google analytics custom variables for my Drupal websites. I make use of the Google analytics module and the Token module on drupal.org. You can find more information about installing these modules on http://drupal.org/project/google_analytics and http://drupal.org/project/token. If you successfully installed these modules, you can continue reading this article.

On the settings page of the google analytics module (admin/config/system/googleanalytics) you can find an area to fill in custom variables. You could fill in a static string but that wouldn't be useful to analyze. Making use of tokens is way more powerful. You could chose one from the default tokens but in our example we are going to make our own. Doing so will give us more flexibility.

To make your own token in Drupal, we have to let Drupal know that we want our own custom token by implementing the hook "hook_token_info".

We start by adding a now type for all our custom google analytics variables. As you can see in the code below, we add our custom tokens to the new type.

<?php
/**
* Implements hook_token_info().
*/
function my_module_token_info() {
 
// new type
 
$info['types']['google-analytics'] = array(
   
'name' => t('Google analytics variables'),
   
'description' => t("Google analytics variables."),
  );
 
// new token
 
$info['tokens']['google-analytics']['user-roles'] = array(
   
'name' => t('User roles'),
   
'description' => t("All the roles that the user has."),
  );
  return
$info;
}
?>

Now that Drupal knows our token. We can add the hook "hook_tokens" that replaces the token with its actual value. In our example, we are returning the user roles. By doing so we can track the page-views separated by roles. You could also use a yet existing token to return the roles of the user but for an example purpose, we are using a custom token.

<?php
/**
* Implements hook_tokens().
*/
function my_module_tokens($type, $tokens, array $data = array(), array $options = array()) {
 
$replacements = array();

  if (
$type == 'google-analytics') {
    foreach (
$tokens as $name => $original) {
      switch (
$name) {
        case
'user-roles':
          global
$user;
         
$replacements[$original] = implode(', ', $user->roles);
          break;

      }
    }
  }

  return
$replacements;
}
?>

After adding the token, you have to clear the cache so that Drupal searches for the new token. After doing so, you have to add it on the Google analytics settings page (admin/config/system/googleanalytics). On the screenshot below, you can see that I have added the new token to the first line of custom variables. I named it "Roles". This name appears in the top-level Custom Variables report of the Analytics reports.

After saving the settings page, we get this extra code on every page (inside the Google analytics script)

_gaq.push(['_setCustomVar', 1, "Roles", "authenticated user, administrator", 3]);

This is exactly what we wanted. Now start thinking what would be useful to track on you website and make an extra token for it. This gives you a powerful way of tracking states/elements on you website. There are some websites with good use cases like http://techpad.co.uk/content.php?sid=166

Published on: 

Comments

juliangb (not verified)

You could also do this by using the existing token "[current-user:role-names]".

Do you find that your own token is better?

Bruno Goossens

Yes, I did mention this in my article. The token I created in this example is just a way to show how to track custom data, It was probably better to chose some data that is not yet in an other token to make a better example. On a website I worked on, I had to track the webform step so that the customer could see at what step the most visitors stopped filling in the form. At the end of the article, you can find a link with more use cases.

rooby (not verified)

Regarding tracking webform steps, I don't believe you can use the google analytics goals/funnels functionality with variables (I might be wrong).

For tracking webform steps I used page views for non-existent urls and then set up funnels in google analytics for those urls so you get the awesomeness of google analytics funnel graphs etc.

Just be aware of the potential to double record page views (number of hits) for those pages.

Sil (not verified)

Great article, thanks. Could you make the top image a bit bigger so I can read what the red arrow points to? (or maybe link it to the bigger image)

Justaman (not verified)
Thanks! great Tutorial I Don't see why you doing the foreach and switch in my_module_tokens should it be:
<?php
/**
* Implements hook_tokens().
*/
function my_module_tokens($type, $tokens, array $data = array(), array $options = array()) {
    if (
$type == 'google-analytics') {      
        global
$user;
        return array(
$tokens['user-roles'] => implode(', ', $user->roles));
    }
}
?>
?
Bruno Goossens

The foreach and the switch is useful if you add more tokens. You can also find the same code in the example module for tokens.

Tommy (not verified)

Just wanted say great article. Thanks!

José Alves (not verified)
Hi, how to extend the custom variables functionality to views based on contextual filters parameters (url params)?
Bruno Goossens
You can get the parameters from a contextual filter with the $_GET variable. You can return this in you token replacement and send it to google analytics.

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.

Filtered text

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <span> <div>
  • To post pieces of code, surround them with <code>...</code> tags. For PHP code, you can use <?php ... ?>, which will also colour it based on syntax.
  • Web page addresses and e-mail addresses turn into links automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.