Drupal Conditional PHP if admin or user has certain role

帅比萌擦擦* 提交于 2019-12-23 17:49:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!