问题
The following will do 'something' if the user is admin.
<?php if (($is_admin)) : ?>
do something
<?php endif; ?>
How can I change this so 'something' will happen if the user is admin or has a certain role? Thanks
回答1:
Roles are stored in $user->roles. To check "if the user is admin or has a certain role" you can simply:
if ($is_admin || in_array('some_role', $user->roles)):
回答2:
For checking if the user belongs to one or more roles, you can do:
global $user;
$allowed_roles = array('customer', 'administrator');
if(count(array_intersect($user->roles, $allowed_roles)) > 0){
// do something useful here
}
回答3:
function user_has_role($roles) {
return !!count(array_intersect(is_array($roles)? $roles : array($roles), array_values($GLOBALS['user']->roles)));
}
using this function you can check if user has one or more role. although it may be useful as 'access callback' value
来源:https://stackoverflow.com/questions/7324506/drupal-conditional-php-if-admin-or-user-has-certain-role