Segmenting Drupal Users By Role in Google Analytics

We use Google Analytics and Drupal at work. We have been tracking our website usage for quite a while now, but we had no idea what percentage of our visitors were staff. We have 13 main locations, so IP filtering could’ve gotten us most of the way, but staff members do work from home and on the road quite a bit too. In the end I decided that the best route would be to use Google Analytics _setCustomVar funcitons to record the data we wanted.

Staff members at work have the role “staff”, so that’s what I wanted to select on.

I decided to set two custom vars. The first one would be a session level scope which should roughly identify if the user is logged in to the website. The second is a visitor level var which will track the user even if they log out or reboot their computer.

The way I made this happen was by putting the Google Analytics code in the footer block of the website, below the copyright notice. First set the The standard Google Analytics javascript goes in first, then we set our block to use PHP, and use PHP to conditionally add the custom vars we want.

<script type="text/javascript">
 var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
 document.write(unescape("%3Cscript src='" + gaJsHost + "' type='text/javascript'%3E%3C/script%3E"));
<script type="text/javascript">
 var pageTracker = _gat._getTracker("UA-XXXXXXX-X");
 global $user;
 if($user->uid && in_array('staff',$user->roles)){
 // Identify this session as a logged in staff member session
 $js_string .= 'pageTracker._setCustomVar(2,"LoggedInStaff","True",2);' . "\n";  

 // Identify this as a staff computer, even if they're not logged in so we
 //can see how many staff use the website while not logged in
 $js_string = 'pageTracker._setCustomVar(1,"StaffComputer","True",1);' . "\n"; 

 print $js_string;
 } catch(err) {}

It ended up being very simple. Check if the $user object has a uid, if so it’be cause they’re logged in. Then check if the role we are interested in is in the user’s roles. If that’s the case, then print the conditional JavaScript.

Wait a few hours for some data to show up in Google Analytics and you can create custom segments based on these custom vars we just set up!

This entry was posted in Programming, Projects and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *