Computer Screen

An Introduction to WP-CLI

For the last two years I have been heavily contributing to WP-CLI. WP-CLI is the official command line tool for interacting with and managing WordPress sites. Especially through my work on the wp i18n command, which provides internationalization tools for WordPress projects, I learned more about how people interact with WP-CLI and command line tools in general. With this introductory blog post I intend to show you how easy it can be to use WP-CLI.

Disclaimer: this post is basically the written version of my talk at this year’s WordCamp London. The recorded video should be available soon.

The Command Line

Before we dive right into WP-CLI, I want to introduce you to some general command line basics. This way you can get a better picture of how command line tools are meant to work and why they might respond in a certain way.

Simply put, the command line is a text interface to interact with a computer. Before we had all these graphical user interfaces, the command line prompt is basically the only thing you got when booting up your computer. There you could type in some command that would execute a certain program.

Nowadays the shiny UIs on our computers hide all the complexity underneath. However, the command line still gives you a powerful way to do basically anything on your computer. A big benefit of command line tools is that you can easily automate and even combine them together.

On your computer, you can access the command line using a terminal application. It looks a bit like this:

The terminal with its command line prompt.

What you’ll usually see in the terminal is the command line prompt in the form of the $ (dollar) sign. That’s where you can then enter the name of the application that you want to run — in this case myprogram — and some arguments that should be passed to the program. After that, magic stuff will happen 🙂

$ myprogram --foo="bar" --debug names.txtCode language: JavaScript (javascript)

In all the upcoming examples, you’ll see this $ at the beginning of each line, indicating the command prompt where you would type the commands.

There are essentially three types of command line arguments: named arguments, flags, and positional arguments. Here, we set the value of foo to bar. This is a named argument. Flags are like on/off switches. So passing --debug here would turn on debug mode. Last, names.txt is just a name of a file that we want to pass to the program. You could have many more of these so called positional arguments.

Let’s use a more real-life example! Here’s how you could update literally all of the WordPress sites you manage using three simple commands offered by WP-CLI:

# Update all your WordPress sites at once
$ wp @all core update
$ wp @all plugin update --all
$ wp @all theme update --allCode language: PHP (php)

Of course you could further tweak this. For example if you only want to do minor updates from let’s say WordPress 5.2 to 5.2.1 instead of 5.3. That would just require you to type a few more letters.

Just imagine how long it would take you to update all your sites by manually clicking on some buttons.

Command Line Building Blocks

While WP-CLI is a command that you first need to install, there are already plenty of commands available on your system. Here’s a short list of some more common ones:

  • List directory contents: ls
  • Print working directory: pwd
  • Change directory: cd
  • Remove files: rm
  • Make new directory: mkdir

There are tons of these little commands. And as you might notice from this list here, these commands all have a very simple job to do. Creating such small programs is actually one of the Unix philosophies: write programs that do one thing and one thing only, and write programs that work together.

I often like to compare them to Lego bricks. A single command only gets you so far. However, when you combine them together, you can build some pretty cool stuff!

In this post I only cover the basics of the command line. To learn more about it, I suggest checking out resources like Codecademy tutorials or perhaps LinuxCommand.org.

Exit Codes

Something that might be perceived as odd at first is that some commands don’t return anything. At first glance, you might think that they don’t work, since nothing is happening. One example for that is the WP-CLI command to check if your WordPress site has already been installed or if you have yet to set it up: wp core is-installed. Although nothing is being output to you directly, the command’s exit code will tell you the site’s installation status.

To quickly see the exit code of your previously run command, you can use the dollar question mark variable:

$ wp core is-installed
$ echo $?
0Code language: PHP (php)

It’s good to know that every command has an exit code. On POSIX systems, an exit code of 0 means everything is OK (success), whereas any number from 1 to 255 is a non-success (or error, if you so will). Some commands only use 0 and 1 as exit code though, as they don’t have for more.

Most of the time, you won’t need that $? variable to find out the exit code, as it’s mostly useful in combination with other commands.

Command Chaining

A very simple such combination would be command chaining. For example, instead of running commands like mkdir and cd on their own, you can write things like mkdir test && cd test to say “create a new directory and when that is successful, switch to that directory”. Or the other way around: “create a new directory or print a nice error message when something goes wrong” could be written as mkdir test || echo "Oops".

So these && and || operators actually check for these exit codes:

$ wp core is-installed && wp core update
$ wp post exists 123 || echo "Post does not exist"Code language: PHP (php)

Pipes

Another way of combining programs are pipes, or pipelines. Simply put, pipes let you use the output of a program as the input of another one. Here are a few examples:

  • Filter lists using regex: ls -l | grep ".php$"
  • Get the word count: echo "These are four words" | wc -w
  • Delete temporary files: find . -name '*.tmp' | xargs rm

The one command I like most there is the last one, xargs. In that example, the find command returns a list of all temporary files that one might want to clean up. xargs then takes this list and runs the rm command on each of the files to delete them individually.

Here’s how you could use xargs in combination with WP-CLI:

$ wp site list --field=url | xargs -n1 -I % wp --url=% option update my_option my_valueCode language: PHP (php)

This will retrieve a list of all sites in a network, and then for each of the sites it adds a specific option to the database. Some more examples with WP-CLI and xargs can be found in the handbook. That is also a great place to look up the exact arguments needed for xargs.

Scripting

Many times, you need to run multiple commands in a row or run them very often. To make this easier, you can create a shell script for these tasks.

A shell script is basically a text file with one or more commands that are executed in a linear order. You can also add some code comments to the script to make it easier to comprehend. Here’s a simple example:

#!/bin/bash

# Update all WordPress sites at once

echo "Start updates..."
wp @all core update
wp @all plugin update --all
wp @all theme update --all

echo "Finished!"Code language: PHP (php)

Now, we can just execute this single script instead of having to type all commands manually every time we need to use it:

$ my-first-script.sh

Start updates...
# [...]
Finished!Code language: PHP (php)

This also makes it very easy to share, drop on a server, put on GitHub for collaboration, and so on.

Meet WP-CLI

With these fundamentals set, let’s add some WordPress to the mix and see what we can do with WP-CLI.

First of all, many web hosts nowadays install WP-CLI on all of their servers by default. That means it is immediately available and you don’t have to worry about installing it first and setting everything up.

Second, it is very intuitive to use and has extensive documentation for all the available commands and configuring WP-CLI. This way you can get started quickly, even if you are not a developer.

Finally, the goal of WP-CLI is to provide the fastest way to perform any task in WordPress. So if you are ever in doubt about how to do something in WordPress, you might want to check the command line first.

Getting Started

To get started with WP-CLI, open the built-in documentation using wp help. This will give you a general help screen with a list of commands. You can also get a help screen for a specific command, e.g. by typing wp help post.

For information about your WP-CLI environment, you can use wp cli info. And if that command tells you that your version of WP-CLI is out of date, you can simply update it using wp cli update.

Bundled Commands

When you install WP-CLI, it comes with a long list of useful commands. These are already built-in and cover pretty much all aspects of WordPress. You can manage things like posts, comments, and plugins all through the command line.

But there are also some commands that don’t actually require WordPress, because they work independently of a specific WordPress site. One such command is wp i18n, which I’ve mentioned at the beginning of this article.

Note: You can learn more about the wp i18n command in my blog post about internationalization in WordPress 5.0.

To give you an idea of what you can do with WP-CLI, here’s a list of some more or less common examples:

  • Delete all products: wp post delete $(wp post list --post_type='product' --format=ids)
  • Generate some dummy users for testing: wp user generate --count=500
  • Show all active plugins: wp plugin list --status=active
  • Perform a search and replace operation on the database: wp search-replace 'http://example.test' 'http://example.com' --skip-columns=guid
  • Generate translation files: wp i18n make-pot

Global Parameters

There are some arguments that you can pass to all commands offered by WP-CLI. For example, if you like its output to be more quiet, you can suppress some of the informational messages WP-CLI usually prints using --quiet. Or for the other way around, you can use the --debug flag to get a little more extra information.

Super helpful is also the ability to skip some plugins or even themes using --skip-plugins and --skip-themes. Some plugins might not always work well in combination with WP-CLI. This flag this allows you to disable a plugin or theme for just this one command.

Learn more about global parameters.

Common Use Cases

Install a WordPress Site

WordPress praises itself for its famous 5 minutes installation procedure. The truth is, it’s often a bit longer than that. But with WP-CLI, we can actually bring this time down to seconds.

Using just three WP-CLI commands we can download WordPress, set up wp-config.php and run the whole installation procedure, without even having to open a browser.

$ wp core download --locale=en_GB
$ wp core config --dbname=mynewsite --dbuser=root
$ wp core install --url=mynewsite.dev --title="My Site"Code language: JavaScript (javascript)

Using the third-party wp login command you could even generate a link that automatically logs you in afterwards.

Perform all Updates on a Site

This is similar to the example I gave earlier, but now just for a single site:

$ wp core update
$ wp plugin update --all
$ wp theme update --all

Regenerate Thumbnails

Another useful command that comes in handy when changing image sizes is wp media regenerate. There’s no need to install a plugin for this and performing this tedious task in the browser. With WP-CLI you can do it all on the command line and let it run in the background. You can even automate it using a cron job.

$ wp media regenerate --yes --only-missing

Site Migrations

WP-CLI is also an ideal tool for site migrations. You can not only export and import your database for an easy backup of your site. You can also use it when changing your domain name or when going from HTTP to HTTPS.

$ wp db export
$ wp db import
$ wp search-replace 'https://old.blog' 'https://new.blog' --skip-columns=guidCode language: JavaScript (javascript)

Evaluate Code

This one is more for developers I guess. wp eval allows you to quickly execute some PHP code, which is very useful for debugging. It allows you to quickly find out the value of a variable or run a function. This is especially useful if there is no WP-CLI command for a certain feature yet

$ wp eval 'echo WP_CONTENT_DIR;'
/var/www/wordpress/wp-contentCode language: JavaScript (javascript)

Flush Rewrite Rules

When you installed some plugins that messed with your permalinks in some way, and now your URLs aren’t working properly anymore, you can simply run wp rewrite flush to clean up and regenerate the permalinks.

Configuration Files

Many aspects of WP-CLI can be tweaked through configuration files. WP-CLI looks for these in various locations. This way you can have a global configuration file, as well as per-project configurations. The lookup order is like this:

  1. wp-cli.local.yml
  2. wp-cli.yml
  3. ~/.wp-cli/config.yml

A simple configuration file could look like this. Here you just tell WP-CLI where your site is located and what the site URL is:

path: wp-core
url: https://pascalbirchler.com
user: Pascal
disabled_commands:
  - plugin installCode language: JavaScript (javascript)

I think it’s really cool that it allows you to disable certain commands. This way you can prevent users from running commands that could potentially break your site if not executed with care.

Aliases

Configuration files can also contain defaults for any subcommand, as well as aliases to one or more WordPress installs. This way you can run WP-CLI on a server without having to memorize credentials and log into that server first.

Aliases can even reference other aliases to create alias groups. Using just one alias you can simultaneously run a command against multiple sites on different servers.

@staging:
  ssh:
  user:
  path:
@production:
  ssh:
  user:
  path:

@mywebsite:
  - @staging
  - @production

This way you can use wp @mywebsite <command> to run something across both the staging and production environments of a site.

Note: WP-CLI automatically creates the @all alias group you’ve seen in previous examples, which allows you to run a command across all your websites.

Extending WP-CLI

WP-CLI is very powerful and contains a lot of super helpful commands. However, if in any case these are not enough for you, you can also extend WP-CLI with third-party commands.

WP-CLI is very modular. All the built-in commands are actually separate packages, and adding more commands just means adding another package to the mix. You could even install a package that overrides one of the built-in commands. Thanks to this modularity, the WordPress community is steadily creating new commands for WP-CLI.

The commands you need to know:

  • List all installed packages: wp package list
  • Install a new package: wp package install <package>
  • Remove an existing package: wp package uninstall <package>
  • Update installed packages: wp package update

In these examples, <package> refers to name of the GitHub repository the package is located at, or a fully-qualified URL.

After adding a new package, you’re all set and you can immediately run it. No need to restart your computer or anything.

Magic Login Links

As mentioned above, the wp login command allows you to log into WordPress with secure passwordless magic links. These can be generated on the fly or even sent via email.

$ wp package install aaemnnosttv/wp-cli-login-command
$ wp login create <user>Code language: HTML, XML (xml)

Vulnerability Scanner

10up created a command that checks your installed plugins and themes against the WordPress vulnerability database. This way you can quickly check whether your site is potentially at risk for getting hacked.

$ wp package install 10up/wp-vulnerability-scanner
$ wp vuln status

Image Optimization

Another handy command I recently found allows you to do lossless image optimizations on all your media files in WordPress.

Image optimization is resource and time intensive just by its nature. It makes sense to run this on the server at a convenient time. Plus, this way you don’t have to install the same image optimization plugin on all of your WordPress sites.

$ wp package install typisttech/image-optimize-command
$ wp media regenerate
$ wp image-optimize batch

Write Your Own Custom Command

Of course, you can also create your very own WP-CLI command … using nothing less than WP-CLI itself!

WP-CLI ships with commands to scaffold new plugins, themes, Gutenberg blocks, and even WP-CLI commands. All scaffolded commands will contain proper documentation, some initial boilerplate code, and even the complete testing setup.

What’s Currently Missing?

Need some inspiration for your first WP-CLI command? I recommend checking out the project’s ideas repository where people can suggest new features. Currently high on the list are commands for the built-in privacy management tools, as well as commands related to Gutenberg.

Once you have found something you want to create a command for, you can use the powerful wp scaffold package command to bootstrap your new package. Yes, that’s a command to create another command! 🤯

Note: The scaffold command is not yet fully updated for the new WP-CLI 2.0 infrastructure, so it currently is also worth checking out other existing commands like wp maintenance-mode to see how they’re constructed.

Further Reading

Wanna learn more about WP-CLI? I recommend checking out the project’s blog and handbook on make.wordpress.org/cli. There’s also a #cli Slack channel where you can ask questions and contribute back to WP-CLI. And of course, all the code of WP-CLI can be found on GitHub.


Many thanks to Alain Schlesser for maintaining WP-CLI and striving to make it easier for people to use WP-CLI. His excellent presentation at WordCamp Berlin 2017 served as an inspiration for this post.

Thanks to Alain and John Blackbourn for proofreading this post and giving valuable feedback.


Comments

6 responses to “An Introduction to WP-CLI”

  1. […] Pascal Birchler publicou uma postagem de 3000 palavras sobre uma introdução ao WP-CLI. […]

  2. […] An Introduction to WP-CLI – Introductory article that introduces the main concepts and some popular use cases of WP-CLI. […]

  3. how to select post format eg video , audio , image , gallery while posting a content using wp-cli wp post create

    1. Since post formats are stored in a taxonomy, you can use the `–tax_input` argument when using `wp post create`, e.g. `wp post create –tax_input='{“post_format”:[“audio”]}’`.

  4. Where is the simple command to view a file? To like literally open it up and view the code on it? Can that not be done in terminal? Does it have to be done in a file editor opened thru CLI?

    1. You can use commands like `cat`, `head`, or editors like `vim` or `nano` to view files. There’s a lot of these utils and they’re not specific to WordPress or WP-CLI.

Leave a Reply

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