Friday, February 6, 2009

How to find what roles user has in Drupal

User object in Drupal has a roles array and all you have to do is to check if this array has the role you want.

Here is an example:

<?php
global $user;
$user->roles[ "ROLE_ID" ] = "ROLE_NAME";

// You can traverse through the array
// and check if user has the role you want
foreach($user->roles as $rid => $role){
if($role == "role_i_want"){
// Do something
}
}
?>

1 comment:

  1. A little more concise:

    if (in_array('administrator', array_values($user->roles))) {
    // Do something.
    }

    Found it here: http://www.richardcastera.com/blog/drupal-check-if-a-user-has-a-specific-role

    ReplyDelete