WordPress:检查前端自定义用户角色

3

我想在用户拥有自定义用户角色时显示一些消息。它可以使用原生用户角色,但不能使用自定义用户角色。这是我的代码:

<?php
$user_ID = get_current_user_ID();
$user = new WP_User( $user_ID );
$current_user = $user->roles[0];

if( $current_user == 'client' ){
   echo 'hello client';
} else {
   // do nothing
}
?>

任何帮助都是受欢迎的,谢谢!
2个回答

2

如果用户设置了多个角色,上述示例存在问题,因为代码只检查用户设置的第一个角色。

理想情况下,您应该检查用户的任何角色是否与自定义角色匹配:

if ( is_user_logged_in() ) {
    global $current_user;

    if( in_array('YOUR_CUSTOM_ROLE',  $current_user->roles) ) {
        echo 'User has Custom Role';
    } else {
        echo 'User does not have Custom Role';
    }
}

2
你可以尝试这个方法:
if ( is_user_logged_in() )
{
    global $current_user;
    $user_role = $current_user->roles[0];

    if($user_role == 'client')
    {
    // do something
    }
}

is_user_logged_in() 用于检查用户是否已登录。


原来我在创建自定义用户角色时犯了一个错误。不过,你的方法更好、更干净,谢谢! - Luc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接