开发者

Drupal Conditional PHP if admin or user has certain role

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


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)):


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
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜