根据 WordPress 中的多个用户角色显示内容 [英] Show content based on multiple user roles in WordPress
问题描述
我希望显示基于多个不同用户角色的内容.
I am looking to display content based on multiple different user roles.
目的是为两个或三个不同的用户角色显示内容,然后为其他用户角色阻止它,显示一条消息,它只适用于某些登录用户.
The aim is to display content for two or three different user roles, and then block it for other user roles, displaying a message that it is only for certain logged in users.
到目前为止,我有以下几点:
So far, I have the following:
<?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 语句并显示登录表单.
At the moment, the issue I am having seems to be that the code is looking for both the administrator and subscriber roles at the same time and as a result, the if statement is not satisfied and the login form shows.
如果我将 $roles 更改为管理员"或订阅者",它就可以正常工作.
If I change $roles to 'administrator' or 'subscriber', it then works fine.
那么,我将如何搜索数组以显示任一角色,而不是所有角色.
So, how would I search through the array to display either role, not all of them.
谢谢
推荐答案
您可以使用:array_intersect(链接)
You could use: array_intersect (link)
array_intersect 将检查两个数组之间的针($roles
)是否存在于大海捞针($user_info->roles
)中.我已经在我自己的身上进行了测试,效果很好.
array_intersect will check between two array to see if the needle ($roles
) exists in the haystack ($user_info->roles
). I have tested this against my own and works well.
见下文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
数组有一场比赛.
这篇关于根据 WordPress 中的多个用户角色显示内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!