【问题标题】:Show content based on multiple user roles in WordPress在 WordPress 中显示基于多个用户角色的内容
【发布时间】:2016-05-05 17:57:41
【问题描述】:

我希望根据多个不同的用户角色显示内容。

目的是为两个或三个不同的用户角色显示内容,然后为其他用户角色阻止它,显示一条消息,它只针对某些登录用户。

到目前为止,我有以下内容:

<?php 
    global $user_login, $current_user;
    get_currentuserinfo();
    $user_info = get_userdata($current_user->ID);
    $roles = array (
        'administrator',
        'subscriber',
    );

if (is_user_logged_in() && in_array( $roles, $user_info->roles)) {

//content here

} else {

// they aren't logged in, so show them the login form

}
?>

目前,我遇到的问题似乎是代码同时查找管理员和订阅者角色,结果,不满足 if 语句并显示登录表单。

如果我将 $roles 更改为“管理员”或“订阅者”,它就可以正常工作。

那么,我将如何搜索数组以显示任一角色,而不是全部。

谢谢

【问题讨论】:

  • 嗨@rahul-s,感谢您的回复,但我不确定您是否完全阅读了我正在寻找的内容。那是我正在使用的代码,但我需要它用于多个用户角色,而不仅仅是一个。该帖子仅适用于管理员。不过谢谢

标签: php wordpress


【解决方案1】:

您可以使用: array_intersect (link)

array_intersect 将检查两个数组之间的针 ($roles) 是否存在于大海捞针 ($user_info-&gt;roles) 中。我已经用自己的方法对此进行了测试,并且效果很好。

见下文array_intersect的用法。

<?php 
    global $user_login, $current_user;
    get_currentuserinfo();
    $user_info = get_userdata($current_user->ID);
    $roles = array (
        'administrator',
        'subscriber',
    );

if (is_user_logged_in() && array_intersect( $roles, $user_info->roles)) {

echo 'success';

} else {

echo 'failure';

}
?>

示例 1:LINK $roles 数组不匹配。

示例 2:LINK$roles 数组有一个匹配项。

【讨论】:

  • 嗨@jamie-sterling,看准了,正是我需要的。这对我也有效,感谢您的帮助!
  • @damienoneill2001,很高兴为您提供帮助!
猜你喜欢
  • 2014-12-20
  • 2016-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 2014-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多