Remove an administrator from 58 networks at once with WP-CLI

Ok, so this is super specific and probably won’t come in handy for you. But it’s another example of how quickly you can perform a task using WP-CLI.

At WSU, we currently have 58 networks configured in WordPress multisite.

  • Global administrators are users that have been set under the site_admins option on network 1.
  • Network administrators are users that have been set under the site_admins option on any other network.

Depending on the page view, these are used to make up what WordPress validates as is_super_admin(). See WordPress core ticket #37616 for an eye into how this will get a lot better soon.

One of our excellent interns has graduated and we needed to remove him from ~25 different networks. Because I rushed the original UI on adding network administrators, there’s no great way to remove them.

Enter WP-CLI:

wp site option list --field=site_id --search=site_admins | xargs -n1 -I % wp eval 'if ( $sa = get_network_option( %, "site_admins" ) ) { if ( $tk = array_search( "old.username", $sa ) ) { unset( $sa[ $tk ] ); update_network_option( %, "site_admins", $sa ); } }'

WP-CLI isn’t really multi-network aware out of the box, so the wp site option list command will output all options for all networks. We can use this to our advantage by having only site_id output for only the site_admins option on each network.

We then pipe this to xargs and use wp eval to run arbitrary PHP code. This code retrieves the current site_admins data for the given network, removes the old user from the array, and then updates the network option with the new value.

This is a prime candidate for packing into some code and turning it into an actual command—wp network admin remove or something—but it does the trick for now!

And if we haven’t written a better UI or WP-CLI command by the time somebody else needs to be removed, then referring to this post and using the command will take 10 seconds instead of the 5 minutes it  took to make it in the first place. 🙂

Update: Daniel pointed out wp super-admin, which I hadn’t noticed before. This will take a --url argument, so if you know a URL on the network, then you can pass that and it will work. There’s no great way (that I know of yet) to generate list of URLs that covers all networks, but I started an issue on the WP-CLI repo to start figuring that out.

Leave a Reply