Run a WP-CLI command one or more sites on WordPress multisite

If you like my WordPress work, check out my new plugin, Bylines. Thanks!

WP-CLI uses the --url=<url> global parameter to specify the request context for the execution of a command. Behind the scenes, --url=<url> sets the $_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI'] and related request context variables. WordPress then interprets these variables to understand which site to load on a multisite network.

Individual site

If you have a site with slug blog on a WordPress multisite instance using subdomains, you can use the full URL to run a command against the site:

wp --url=blog.example.com

Think of the --url=<url> parameter as any URL you can put in your browser.

Multiple sites

Need to run a given WP-CLI command against multiple sites on a WordPress multisite install? You can do so using a combination of wp site list and xargs.

Here’s an example where wp option update is run against all sites:

wp site list --field=url | xargs -n1 -I % wp --url=% option update my_option my_value

Deconstructing this example:

  1. wp site list --field=url produces a list of URLs for all of the sites on the network. You can configure the list of URLs by filtering based on the supported arguments.
  2. The | operator passes the results from wp site list to xargs, a utility which takes lines of input and passes them to some command.
  3. xargs -n1 -I % wp --url=% option update my_option my_value runs wp option update my_option my_value against a given site, identified with --url=<url>. The % is a placeholder that’s replaced with a URL from the site list.