在WordPress中显示基于多个用户角色的内容


Show content based on multiple user roles in WordPress

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

目的是显示两个或三个不同用户角色的内容,然后阻止其他用户角色的内容,显示一条消息,指出它仅适用于某些登录用户。

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

<?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更改为"管理员"或"订阅者",它就可以正常工作。

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

谢谢

您可以使用:array_intersect(链接)

array_intersect将检查两个阵列之间,看看大海捞针($user_info->roles)中是否存在针($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:链接$roles数组不匹配。

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