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

问题描述 投票:1回答:1

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

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

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

<?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更改为'administrator'或'subscriber',那么它可以正常工作。

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

谢谢

php wordpress
1个回答
4
投票

你可以使用:array_intersect (link)

array_intersect将在两个数组之间进行检查以查看大海捞针($roles)中是否存在针($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';

}
?>

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

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

© www.soinside.com 2019 - 2024. All rights reserved.