【问题标题】:Wordpress: check for custom user role in frontendWordpress:在前端检查自定义用户角色
【发布时间】:2015-12-20 11:16:55
【问题描述】:

我只是想在用户具有自定义用户角色时显示一些消息。它适用于本机用户角色,但不适用于自定义角色。这是我的代码:

<?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
}
?>

欢迎任何帮助,谢谢!

【问题讨论】:

    标签: php wordpress user-roles


    【解决方案1】:

    你可以试试这个:

    if ( is_user_logged_in() )
    {
        global $current_user;
        $user_role = $current_user->roles[0];
    
        if($user_role == 'client')
        {
        // do something
        }
    }
    

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

    【讨论】:

    • 原来我在创建自定义用户角色时犯了一个错误。不过,你的方式更好/更干净,谢谢!
    【解决方案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';
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 1970-01-01
      • 2021-06-09
      • 2011-02-28
      • 2018-03-09
      • 2016-11-13
      • 2015-07-21
      • 2015-06-05
      • 1970-01-01
      相关资源
      最近更新 更多