Skip to main content

Disable Google Analytics by Role, User, or nid

If you utilize the code to disable Google Analytics by role or user within the module, it leaves you no easy way to exclude individual nodes. Getting the node id (nid) and adding a few extra lines of code that will check against a predefined array results in new code:

<?php
global $user;

// These are the roles, uid, and nid which should not see this module
$notallowed_role = array('Administrator','Contributor','Forum admin');
$notallowed_uid = array(1,8);
$notallowed_nid = array(1,2,3);

// Assume they can see it to start
$valid=TRUE;

// Go through each role the user is in and, if we hit a role 
// that is not allowed to see it, set valid to false
foreach($user->roles as $role){
  if(in_array($role, $notallowed_role)) {
    $valid=FALSE;
  }
}

// Check the uid array for users that should not see this block
if(in_array($user->uid, $notallowed_uid)) {
  $valid=FALSE;
}

// Get node id
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  // Check the nid array for users that should not see this block
  if(in_array($nid, $notallowed_nid)) {
    $valid=FALSE;
  }
}

// If no roles were hit that aren't allowed, 
// this will still be true. Otherwise it will be false.
return $valid;
?>

Share this post