简体   繁体   中英

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:

$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.

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

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().

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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