我希望根据多个不同的用户角色显示内容。
目的是为两个或三个不同的用户角色显示内容,然后为其他用户角色阻止它,显示一条消息,它仅适用于某些登录用户。
到目前为止,我有以下几点:
<?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
}
?>
Run Code Online (Sandbox Code Playgroud)
目前,我遇到的问题似乎是代码同时查找管理员和订阅者角色,因此不满足 if 语句并显示登录表单。
如果我将 $roles 更改为“管理员”或“订阅者”,则它可以正常工作。
那么,我将如何搜索数组以显示任一角色,而不是所有角色。
谢谢
您可以使用: array_intersect(链接)
array_intersect 将在两个数组之间检查以查看针 ( $roles) 是否存在于 haystack ( $user_info->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';
}
?>
Run Code Online (Sandbox Code Playgroud)
实施例1:LINK的$roles阵列不匹配。
实施例2:LINK所述$roles阵列具有一个匹配。
| 归档时间: |
|
| 查看次数: |
2622 次 |
| 最近记录: |