Fun with WP-CLI

A random collection of things you perhaps didn’t know you could do with WP-CLI.

Maybe you’ve imported an image before, but did you know you can import a whole directory just as easily? For example, if the directory is named ‘images’:

wp media import images/*

Sometimes you need to run a command based on a result set from another command. In many cases, you can do that by nesting the one in the other. For example, if you want to change the password for all users with the ‘author’ role.

wp user update $(wp user list --role=author --field=ID) --user_pass=password

Or go crazy and regenerate media for the featured image of all sticky posts.

wp media regenerate $(wp eval 'foreach( wp_parse_id_list( get_option("sticky_posts") ) as $id ) { echo get_post_thumbnail_id($id). " "; }')

Trying to run a command for each site in a multisite doesn’t have to be a chore. A little bash script can speed things along.

#!/bin/bash

for url in $(wp site list --field=url)
do
	wp theme activate twentyfourteen --url=$url
done

Save that to a file, and run with bash: bash filename

You can do that in a one-liner as well, but that can make it harder to see what you’re doing, especially with more comprehensive commands.

for url in $(wp site list --field=url); do wp theme activate twentyfourteen --url=$url; done

3 thoughts on “Fun with WP-CLI”

  1. Thanks Kailey!

    I’ve only recently started to play around with piping data in wp-cli commands. Do you know if there are more in-depth resources on advanced wp-cli usage anywhere?

    1. I thought there was a page in the WP-CLI wiki, but I’m not finding it. Other than that, I’m not aware of a particular source.

      Lots of people sharing one snippet at a time, and there’s a handful of more advanced examples in the internal documention. Like in wp help option update there’s this:

      # Update an option by reading from a file
      wp option update my_option < value.txt
      
      # Update one option on multiple sites using xargs
      wp site list --field=url | xargs -n1 -I {} sh -c 'wp --url={} option update 
      
  2. Awesome write up. The snippets for running commands across all blogs on a multisite network are very useful.

Leave a Reply

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

%d bloggers like this: