WP-CLI – Managing WordPress From The Terminal

By , Updated: June 5, 2017

wp cli

For most of its life, WordPress has been built using a simple code-base with a dash of object oriented PHP being the most abstract system. In the past few years however this is changing for the better. From unit testing to CSS preprocessing and command line tools, more and more developer-friendly assets are popping up.

In this article we’ll look at one of my favourites: WP-CLI. WP-CLI is a command line tool for managing many-many aspects of a WordPress installation. It can add/remove users, posts, categories, insert test data, search and replace in the database, and much more! Let’s take a look.

If you have a Kinsta account on our new Google Cloud based architecture you have access to WP-CLI already, simply SSH into your server to get started.

Getting WP-CLI

To get started you’ll need to install WP-CLI – a very simple process. The steps for Linux and OSX are the following, issue these three commands one after the other:

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

If something goes wrong or you are on Windows refer to the basic instructions or the alternative installation methods.

Once done you should be able to issue the wp --info command and get a meaningful response.

The process is the same if you want to install WP-CLI on your server. Kinsta has WP-CLI installed by default although you may not be able to access your server via SSH just yet, the feature is coming soon though!

The Basics Of WP-CLI

The idea of WP-CLI is that it gives you access to common (and not so common) tasks via the command line. This is powerful in and of itself, but can give you even more control and speed gains when using bash scripts.

Bash scripts allow you to run a sequence of commands with a single command. You could type bash install-and-setup.sh and get the following result:

  • Download WordPress
  • Create and populate wp-config.php
  • Create the database
  • Install WordPress
  • Install and activate any plugins you need
  • Install and activate a theme
  • Download and add test content

These would be the steps I would take to create a new test environment for a project. Normally it would take me 5-10 minutes at least, especially if there are a few plugins involved. Issuing a single command is obviously a lot faster.

Commands In General

If you are used to working in the terminal there’s nothing special about WP-CLI for you. Commands always start with wp followed by a command and subcommand, followed by required and optional parameters, something like this:

wp command subcommand requiredparam --optionalparam --optionalparam2=value

Let’s install a theme to see how this works with a real command:

wp theme install sorbet --activate

This will install and activate the Sorbet theme on your WordPress installation.

Note that WP-CLI will work with the WordPress installation you are currently in in the terminal. If you switch directories to go to another WordPress installation, it will work with that one.

Useful Examples

That was WP-CLI in a nutshell! While there are a few advanced things you can do, which we’ll get to in a moment, you already know enough to get started and do whatever you need to. I recommend taking a look at the commands list, try some of them out. We’ll take a look at some useful stuff here, then move on to using WP-CLI over SSH and using bash scripts.

Installing WordPress

I use WP-CLI a lot to set up test environments, the first step of which is a vanilla installation. Here is a list of commands I run:

wp core download
wp core config --dbname=mydbname --dbuser=mydbuser --dbpass=mydbpass --dbhost=localhost --dbprefix=whebfubwef_ --extra-php <<PHP
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
PHP
wp db create
wp core install --url=http://siteurl.com --title=SiteTitle --admin_user=username --admin_password=mypassword --admin_email=my@email.com

Note how cool this is! The most recent version of WordPress is downloaded using the first command. The second command sets up the config file with the database access and some additional PHP at the end. The additional constants make sure we have our debugging options on for testing.

Recommended reading: An In-depth View of the wp-config.php file – How to Configure WordPress

The third command creates the database (WP-CLI uses the database access info from the config file) and finally we install WordPress using a couple of parameters.

Installing Multiple Plugins

To install multiple plugins you can simply pile on parameters. Here’s an example that downloads and activates 3 plugins:

wp plugin install advanced-custom-fields jetpack ninja-forms --activate

Note that the plugin names come from their name in the repository. The easiest way to figure this out is to visit their page and look at the URL or to use wp plugin search searchterm which will give you a list in the terminal.

Even cooler, you can install plugins from remote files, not just the repository which is handy if you’re developing a plugin, or using a premium plugin. The following command installs two plugins from the repository and one from an Amazon S3 server.

wp plugin install advanced-custom-fields jetpack https://d1qas1txbec8n.cloudfront.net/wp-content/uploads/2015/06/23073607/myplugin.zip --activate

Database Search And Replace

One of the main reasons it is difficult to migrate a site by just copy-pasting a database is that the database contains serialized arrays. If you need to replace all instances of http://testsite.com with http://livewebsite.com your serialized arrays will not make sense because the string count won’t match up.

The search-replace command unserializes arrays first, then performs the search and replace, then re-serializes the arrays. You can get this done with a simple command:

wp search-replace oldstring newstring

Additional parameters allow you to do a lot more, including preview what will be replaced by using --dry-run.

Import And Export

There are two ways to export content with WP-CLI. You can create an XML file, just like the WordPress export tool does, or you can export/import the raw database. I find the later a lot more useful in my daily routine, it comes in handy when syncing sites.

wp db export is all you need to do to create a sql file and wp db import file.sql is all you need to import it. Works like a charm, just be careful not to overwrite anything you need, importing will basically dump the exiting database and use the supplied SQL file instead.

Manage Roles And Capabilities

WP-CLI can manage roles for you pretty easily using the wp role command. This is pretty cool if you want to test how your plugin works with custom roles but you don’t actually create the roles within your plugin.

wp role create organizer Organizer
wp cap list 'editor' | xargs wp cap add 'organizer'
wp cap add 'organizer' 'manage-events'

The commands above will create a new role (Organizer), add all capabilities from the editor role to it and then add a new capability: manage-events.

Generate Test Data

I love all sort of faker-like functions – ones that add dummy content to your site that you can use for tests. WP-CLI has a couple of these built in, here are a few functions that will generate users, terms and posts.

wp user generate --count=5 --role=editor
wp user generate --count=10 --role=author
wp term generate --count=12
wp post generate --count=50

Using WP-CLI Remotely

One of the best things that you can do with WP-CLI is manage your remote WordPress installations. You’ll need to do a little but of setup, but once done it’s a website manager’s dream come true.

Installing WP-CLI-SSH

First of all, you’ll need the wp-cli-ssh addon command. You can install this globally via composer but I’ll show you how to do it manually, just in case some plugins you find don’t support this.

First, go to the .wp-cli directory within your home directory. This can be done easily using the following: cd ~/.wp-cli. Within that folder, create a commands folder if it doesn’t exist.

Next, we’ll pull in the git repository of the command into a folder named wp-cli-ssh. Use the following code: git clone https://github.com/xwp/wp-cli-ssh wp-cli-ssh. If you don’t have the git command installed, refer to the git installation guide.

Finally, go back to the main ~/.wp-cli directory and create a config.yml file (if it doesn’t exist) with the following content:

require:
  - commands/wp-cli-ssh/wp-cli-ssh.php

Once done you should be able to go type wp ssh and see something other than “is not a registered wp command.”.

Configuring Remote Servers

You can configure your servers globally or locally. To configure them globally use the previously mentioned config.yml file. You can also use the wp-cli.yml or wp-cli.local.yml files in your current working directory.

Configuration of servers works something like this, paste this in one of the mentioned files:

ssh:

  staging:
    cmd: ssh %pseudotty% username@server.com %cmd%
    url: http://myseite.com
    path: /www/path/to/site/root

Once all this is done you can type the following command to update WordPress on your remote site:

wp ssh core update --host=staging

If you own or manage a lot of sites, I think you can see that this is amazing! The script will ask for a password, but if you use RSA keys to log in you can forgo that as well. Take a look at this article to set that up.

Using Bash Scripts

Bash scripts save you even more time by automating tasks. Remember how we needed to type a lot of commands to install WordPress? You can do that with a single bash script. Inside a directory create an install.sh file. Paste the same code we had before inside and save it.

wp core download
wp core config --dbname=mydbname --dbuser=mydbuser --dbpass=mydbpass --dbhost=localhost --dbprefix=whebfubwef_ --extra-php <<PHP
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
PHP
wp db create
wp core install --url=http://siteurl.com --title=SiteTitle --admin_user=username --admin_password=mypassword --admin_email=my@email.com

All you need to do now is type bash install.sh and everything will be done for you, without user intervention. If you manage a lot of sites you can set up all your environments and create a bash script like this:

wp ssh core update --host=clientA
wp ssh core update --host=clientB
wp ssh core update --host=clientC
wp ssh core update --host=clientD

When a new WordPress version comes out, this could save you a lot of time! Since you can do anything you like with WP-CLI you can even update themes and plugins regularly on a number of client sites at once.

Conclusion

WP-CLI really is the developer and website manager’s dream come true. As developers we can create test sites in a jiffy, add test content and do all sorts of import/export magic. Site managers can handle site updates and other tasks for multiple sites with single commands.

If you haven’t already tried WP-CLI I urge you to give it a go. There are also a bunch of community commands like WP-CLI-SSH which add even more great features!

Don’t forget that Kinsta’s new Google Cloud based architecture supports WP-CLI out of the box. If you’d like to try the most modern WordPress hosting architecture and have access to great tools like WP-CLI, try our managed WordPress hosting.