I’m developing a plugin that uses custom capabilities. Some of those capabilities need to be added to all users who are super admins. Currently, I’m using this code:
$supers = get_super_admins();
foreach ( $supers as $admin ) {
$user = new WP_User( 0, $admin );
$user->add_cap( 'my_cap' );
$user->add_cap( 'my_second_cap' );
}
However, I’m concerned that this code is just adding the capabilities to the individual users, as opposed to the role as I usually would. If a new super admin is created, they will not have these capabilities as this function only runs on plugin activation.
Is there a better way of adding custom capabilities to super admins?
Although this isn’t well documented, “Super Admin” is not a role (in that it is not an actual role object). It’s more like a special “status”.
A list of users who are Super Admins (also called “network admins” or “site admins”) are stored in a database site-option record called site_admins
. Generally, adding a capability to the Administrator role is enough since Super Admins are also, de facto, members of Administrator role with all it’s capabilities.
That said, if you specifically need to add a capability only to Super Admins (but not “normal” administrators), it might be better to simply use WordPress’s is_super_admin()
function instead of using capabilities at all, since it is assumed that Super Admins have no restrictions.
If you really need to use capabilities, you should use the grant_super_admin
and remove_super_admin
hooks to add or remove capabilities to/from Super Admin users (respectively) as soon as their Super Admin status changes.
Now as far as changing capabilities for existing Super Admin users, your approach is the best … fetch a list of super admin users, loop through it, and add capabilities to each (although should only need to run that once EVER if you used the above hooks).