On a WordPress multisite installation, I am trying to get the IDs of all superadmins for my site using a function in my theme. (new to multisite here). However, I don't seem to be able to access them with a get_users() function as below:
$roles = [ 'superadministrator','administrator'];
$user_ids = get_users( array( 'role__in' => $roles, 'fields' => 'ID' ) );
There is the get_super_admins() function, but that just seems to return a list of names, not IDs. Also, I would like to just be able to run one query instead of two, so this function isn't ideal.
Super Admin is a special role and unlike the other roles like Administrator and Subscriber, the Super Admin role doesn't get saved to the same WordPress option as the other roles. Instead, the option name is site_admins
and it only stores the username of users who were granted the Super Admin role. So superadministrator
is not a default role in WordPress, i.e. no such role.
But then, since get_super_admins()
returns the usernames saved in the site_admins
option, then you can use that with get_users()
by setting the login__in
arg to those usernames like so:
$user_ids = get_users( array( 'login__in' => get_super_admins(), 'fields' => 'ID' ) );
Or maybe like so, to include all Administrator users:
$admins = get_users( array(
'role__in' => 'administrator',
'fields' => array( 'user_login' ),
) );
$logins = array_merge( get_super_admins(), wp_list_pluck( $admins, 'user_login' ) );
$user_ids = get_users( array(
'login__in' => $logins,
'fields' => 'ID',
) );
But yes, the above requires two get_users()
calls.
[Edit] Note that the blog_id
parameter defaults to the current site ID, so if you want to retrieve the super admins in all sites (or the entire network), then you can set the blog_id
to 0
like so:
$user_ids = get_users( array(
'login__in' => get_super_admins(),
'fields' => 'ID',
'blog_id' => 0, // set it to 0 to search in all sites
) );
However, that could result in performance issues if you have a large network (many sites, users, etc.), so you may need to find an alternative, or a different code for retrieving all the super admins.