How to get role of user

I need to get the role associated with a user — not the “currently logged in user”.

I am using Buddypress (not that should matter to the nature of this question) and I am in the bp_members() loop.

How can I retrieve the role of the user I am reporting on in the loop at any given time?

Thanks.

3

Use the user ID and WP_User:

$user = new WP_User( $user_id );
print wp_sprintf_l( '%l', $user->roles );

Update

/**
 * Get user roles by user ID.
 *
 * @param  int $id
 * @return array
 */
function wpse_58916_user_roles_by_id( $id )
{
    $user = new WP_User( $id );

    if ( empty ( $user->roles ) or ! is_array( $user->roles ) )
        return array ();

    $wp_roles = new WP_Roles;
    $names    = $wp_roles->get_names();
    $out      = array ();

    foreach ( $user->roles as $role )
    {
        if ( isset ( $names[ $role ] ) )
            $out[ $role ] = $names[ $role ];
    }

    return $out;
}

Usage example:

print '<pre>' 
    . htmlspecialchars( 
        print_r( wpse_58916_user_roles_by_id(1), TRUE ) 
        ) 
    . '</pre>';

Array
(
    [administrator] => Administrator
)

Leave a Comment