php 如何在wordpress中获取当前登录用户的角色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1458362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:40:06  来源:igfitidea点击:

How to get the currently logged in user's role in wordpress?

phpwordpress

提问by Ravi

How to get the currently logged in user's role in wordpress?

如何在wordpress中获取当前登录用户的角色?

回答by dnatoli

Assuming you have the user id ($user_id) something like this should work:

假设你有用户 id ($user_id) 这样的东西应该可以工作:

$user = new WP_User( $user_id );

if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
    foreach ( $user->roles as $role )
        echo $role;
}

Get the user id from your session.

从您的会话中获取用户 ID。

回答by Vasiliy Toporov

If you don't know the user id, this function will help you (put it in your theme functions.php file)

如果你不知道用户 id,这个函数会帮助你(把它放在你的主题 functions.php 文件中)

function get_user_role() {
    global $current_user;

    $user_roles = $current_user->roles;
    $user_role = array_shift($user_roles);

    return $user_role;
}

And then, in your template you can get user role by calling get_user_role().

然后,在您的模板中,您可以通过调用 get_user_role() 来获取用户角色。

Found it here.

在这里找到

回答by Ed Williams

function get_role_by_id( $id ) {

    if ( !is_user_logged_in() ) { return false; }

    $oUser = get_user_by( 'id', $id );
    $aUser = get_object_vars( $oUser );
    $sRole = $aUser['roles'][0];
    return $sRole;

}