How can we get a user’s role of a specific site on a Multisite network?

Let’s say the user is a subscriber on the parent site and admin of his own subdomain. Is there a way to only return the role on the parent site or by a specific blog id?

Ex: get_wpmu_user_role($user_id, $blog_id);

1 Answer
1

You can use either WP_User:

$wp_user_obj = new WP_User(
    // $user_id
    get_current_user_id(),
    // $name | login, ignored if $user_id is set
    '',
    // $blog_id
    get_current_blog_id()
);

Or get_users():

$get_users_obj = get_users(
    array(
        'blog_id' => get_current_blog_id(),
        'search'  => get_current_user_id()
    )
);

As they are both blog_id perceptive, if you provide it.

The former will return a WP_User object, the roles are accessible like this:

// array of roles
$wp_user_obj->roles
// access the first or only 
$wp_user_obj->roles[0]

The latter will returns an array of WP_User objects, actually only one object, because the search for a user_id can only return one unique object, the roles are accessible like this:

// array of roles
$get_users_obj[0]->roles
// access the first or only 
$get_users_obj[0]->roles[0]

Another idea, never done that myself, but if you have some kind of shared login and want the information of the current user, then this could work too:

switch_to_blog( $blog_id );
$current_user_at_different_blog = wp_get_current_user();
restore_current_blog();

wp_get_current_user() does return a WP_User object, so the information is accessible like:

// array of roles
$current_user_at_different_blog->roles
// access the first or only 
$current_user_at_different_blog->roles[0]

Last but not least, there is current_user_can_for_blog() which can be used like this:

current_user_can_for_blog( $blog_id, $capability );

The codex page states:

Whether current user has a capability or role for a given blog.

But I strongly suspect like current_user_can() it shouldn’t be used for roles, but capability checks are power- and useful too.

Leave a Reply

Your email address will not be published. Required fields are marked *