Managing WordPress with WP-CLI

Watch out! This tutorial is over 6 years old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

WP-CLI is a command line interface which allows the users to manage their WordPress web sites from the command prompt. Upgrades can be performed, backups can be generated, new posts can be published and most of the regular admin actions can be performed with a set of commands.

This tutorial explains how to use the WP command line interface in order to complete regular administrative tasks like upgrades, database backup creation, plugins and themes installations and removals, publishing and deleting posts, changing site’s URL settings and getting help on chosen commands.  Once complete, you should be able to combine WP-CLI with Bash, Perl or any other scripting language to create powerful web applications.

Note that the template WordPress Server (with WP-CLI) found in Xen Orchestra (obviously) comes with WP-CLI already installed. Fire up an instance for use when following the below.

List the Available WP-CLI Commands

To list all the commands write “wp help” or just “wp”. The following list will be shown:

akismet           Filter spam comments
cache             Manage the object cache
cap               Manage user capabilities
checksum          Verify WordPress core checksums
cli               Review current WP-CLI info, check for updates, see defined aliases
comment           Manage comments
config            Manage the wp-config.php file
core              Download, install, update and manage a WordPress install
cron              Manage WP-Cron events and schedules
db                Perform basic database operations using credentials in wp-config.php
eval              Execute arbitrary PHP code
eval-file         Load and execute a PHP file
export            Export WordPress content to a WXR file
help              Get help on WP-CLI, or on a specific command
import            Import content from a WXR file
jetpack           Control your local Jetpack installation
media             Import new attachments or regenerate existing ones
menu              List, create, assign, and delete menus
option            Manage options
package           Manage WP-CLI packages
plugin            Manage plugins
post              Manage posts
post-type         Manage post types
rewrite           Manage rewrite rules
role              Manage user roles
scaffold          Generate code for post types, taxonomies, plugins, child themes, etc
search-replace    Search/replace strings in the database
server            Launch PHP's built-in web server for this specific WP install
sg                Manage SiteGround Cache
sgphpcompat       Test compatibility with different PHP versions
shell             Interactive PHP console
sidebar           Manage sidebars
site              Perform site-wide operations
super-admin       Manage super admins on WordPress multisite
taxonomy          Manage taxonomies
term              Manage terms
theme             Manage themes
transient         Manage transients
user              Manage users
widget            Manage sidebar widgets

If you want to get detailed documentation, for example for the “wp db export” command, enter the command listed below:

wp help db export

The result will be as follows:

NAME
 
  wp db export
 
DESCRIPTION
 
  Exports the database to a file or to STDOUT.
 
SYNOPSIS
 
  wp db export [<file>] [--<field>=<value>] [--tables=<tables>] [--exclude_tables=<tables>] [--porcelain]
 
ALIAS
 
  dump
 
  Runs `mysqldump` utility using `DB_HOST`, `DB_NAME`, `DB_USER` and
  `DB_PASSWORD` database credentials specified in wp-config.php.
 
OPTIONS
 
  [<file>]
    The name of the SQL file to export. If '-', then outputs to STDOUT. If omitted, it will be '{dbname}.sql'.
 
  [--<field>=<value>]
    Extra arguments to pass to mysqldump
 
  [--tables=<tables>]
    The comma separated list of specific tables to export. Excluding this parameter will export all tables in the database.
 
  [--exclude_tables=<tables>]
    The comma separated list of specific tables that should be skipped from exporting. Excluding this parameter will export all tables in the database.
 
  [--porcelain]
    Output filename for the exported database.
 
EXAMPLES
 
    # Export database with drop query included
    $ wp db export --add-drop-table
    Success: Exported to 'wordpress_dbase.sql'.
 
    # Export certain tables
    $ wp db export --tables=wp_options,wp_users
    Success: Exported to 'wordpress_dbase.sql'.
 
    # Export all tables matching a wildcard
    $ wp db export --tables=$(wp db tables 'wp_user*' --format=csv)
    Success: Exported to 'wordpress_dbase.sql'.
 
    # Export all tables matching prefix
    $ wp db export --tables=$(wp db tables --all-tables-with-prefix --format=csv)
    Success: Exported to 'wordpress_dbase.sql'.
 
    # Skip certain tables from the exported database
    $ wp db export --exclude_tables=wp_options,wp_users
    Success: Exported to 'wordpress_dbase.sql'.

Update WordPress via WP-CLI

First, you need to check the current version of WordPress that you have:

username@servername [~/WordPress/location]# wp core version
4.8

f you would like to upgrade your WordPress core to a newer version, you can do that via the following command:

username@servername [~/WordPress/location]# wp core update
Updating to version 4.8.1 (en_US)...
Downloading update from https://downloads.wordpress.org/release/wordpress-4.8.1-partial-0.zip...
Unpacking the update...
Success: WordPress updated successfully.

Update WordPress Plugins using WP-CLI

If you would like to upgrade any additional plugins or themes on your WordPress website, you could do that with WP-CLI. To check for example the status of the currently installed plugins, use this command:

username@servername [~/WordPress/location]# wp plugin list
+----------------+----------+-----------+---------+
| name           | status   | update    | version |
+----------------+----------+-----------+---------+
| akismet        | active   | available | 3.3.2   |
| google-captcha | active   | none      | 1.31    |
| hello          | inactive | none      | 1.6     |
| jetpack        | active   | none      | 5.3     |
| sg-cachepress  | active   | none      | 3.3.2   |
+----------------+----------+-----------+---------+

We have 5 plugins integrated in our sample installation. There is an upgrade for one of them. To perform an upgrade for that plugin, the following command can be used:

username@servername [~/WordPress/location]# wp plugin update akismet
Enabling Maintenance mode...
Downloading update from https://downloads.wordpress.org/plugin/akismet.3.3.4.zip...
Unpacking the update...
Installing the latest version...
Removing the old version of the plugin...
Plugin updated successfully.
Disabling Maintenance mode...
+---------+-------------+-------------+---------+
| name    | old_version | new_version | status  |
+---------+-------------+-------------+---------+
| akismet | 3.3.2       | 3.3.4       | Updated |
+---------+-------------+-------------+---------+
Success: Updated 1 of 1 plugins.

Install and Activate WordPress Plugins & Themes via WP-CLI

To install and activate a new plugin, execute the commands listed below:

wp plugin install Plugin_Name
wp plugin activate Plugin_Name

You should replace the “Plugin_Name” string with the exact plugin name.

Other Tasks you Can do With WP-CLI

You can write posts directly from the command line. To create a post, use the following command:

username@servername [~/WordPress/location]# wp post create --post_type=page --post_status=publish --post_title='My test post' --post_content='This is a test post'
Success: Created post 18.

If you do not need a certain post you can easily delete it:

username@servername [~/WordPress/location]# wp post delete 18
Success: Trashed post 18.

Example Use Case

This example script could automatically download, configure, and install WordPress core, remove starting plugins, add and activate a specified theme (saved in example-theme.zip), then install and activate a list of plugins you’d prefer to use with new installations.

#!/usr/bin/env bash

#plugins to install and activate (slugs)
WPPLUGINS=( test-plugin1 test-plugin2 test-plugin3 )

echo "Starting WordPress Installation Script"

# Site Name Input
echo "Site Name: "
read -e sitename

# Site URL Input
echo "Site URL: "
read -e siteurl

# Download WP and configure it
wp core download
wp core config --dbname=$dbname --dbuser=root --dbpass=root
wp db create
wp core install --url=$siteurl --title="$sitename" --admin_user="admin" --admin_password="examplePassword123" --admin_email="test@example.com"

# Remove default plugins, install plugins, install Base Theme
wp plugin delete --all
wp theme install example-theme.zip --activate
wp plugin install ${WPPLUGINS[@]} --activate

echo "WordPress installation complete!"

Actually, something quite like this is used by Computer Services to create new WordPress installs for students on the department server.

More details on WP-CLI can be found through the help command and the project’s home page.