简体   繁体   English

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

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

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

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。

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 . 在这里找到它。

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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM