Drupal - Check if a user has a role
Since you already found that post, make sure you also read the comments. It clearly explains why checking for a permission is recommended over checking for a role. When you use permissions, you can assign that permission to multiple roles, which makes your system more flexible. Also, remember that roles can be renamed, which would break your code.
That said, if you want to check for a role, you can do this:
// Load the currently logged in user.
global $user;
// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
// do fancy stuff
}
To check if the current user has a single role or any of multiple roles, a great way is to do:
//can be used in access callback too
function user_has_role($roles) {
//checks if user has role/roles
return !!count(array_intersect(is_array($roles)? $roles : array($roles), array_values($GLOBALS['user']->roles)));
};
if (user_has_role(array('moderator', 'administrator'))) {
// $user is admin or moderator
} else if(user_has_role('tester')){
// $user is tester
} else{
// $user is not admin and not moderator
}
Update for Drupal version >= 7.36
You can use function user_has_role from Drupal API https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_has_role/7.
Try this example:
<?php
function MYMODULE_foo() {
$role = user_role_load_by_name('Author');
if (user_has_role($role->rid)) {
// Code if user has 'Author' role...
}
else {
// Code if user doesn't have 'Author' role...
}
$user = user_load(123);
if(user_has_role($role->rid, $user)) {
// Code if user has 'Author' role...
}
else {
// Code if user doesn't have 'Author' role...
}
}
?>