WordPress Tutorials
WP-CLI Tutorial

WP-CLI Tutorial

WP-CLI is a command line interface that allows users to manage their WordPress websites 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 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. Note that WP-CLI requires SSH access.

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, or 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 stored 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 WordPress 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:


  wp db export


  Exports the database to a file or to STDOUT.


  wp db export [] [--=] [--tables=] [--exclude_tables=] [--porcelain]



  Runs `mysqldump` utility using `DB_HOST`, `DB_NAME`, `DB_USER` and
  `DB_PASSWORD` database credentials specified in wp-config.php.


    The name of the SQL file to export. If '-', then outputs to STDOUT. If omitted, it will be '{dbname}.sql'.

    Extra arguments to pass to mysqldump

    The comma separated list of specific tables to export. Excluding this parameter will export all tables in the database.

    The comma separated list of specific tables that should be skipped from exporting. Excluding this parameter will export all tables in the database.

    Output filename for the exported database.


    # 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

If 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 into 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.

Installation and usage of WP Doctor

WP Doctor is a tool developed to help in diagnosing problems with WordPress websites such as failed update, blank page, upload issues, etc. To use the tool, you should first install it. You can do that by running the command below in your WordPress website’s document root:

wp package install git@github.com:wp-cli/doctor-command.git

After the tool is successfully installed, you can start using it with the wp doctor command.

To check all available options of the command, use:

wp doctor --help

To run all default checks, execute the following command:

wp doctor check --all

The checks that the tool will run are:

core-verify-checksums – Check if WordPress verifies against its checksums.

file-eval – Checks files on the filesystem for regex pattern eval(.*base64_decode(.* which in many cases indicates suspicious code.

cache-flush – Detects the number of occurrences of the wp_cache_flush() function.

autoload-options-size – Warns when autoloaded options size exceeds the threshold of 900 kb.

constant-savequeries-falsy – Confirms expected state of the SAVEQUERIES constant. SAVEQUERIES causes WordPress to save a backtrace for every SQL query, which is a resource heavy operation, thus using SAVEQUERIES in production is discouraged.

constant-wp-debug-falsy – Verifies if wp debug is enabled by checking the state of the state of the WP_DEBUG constant.

core-update – Verifies if the application is up to date. Errors are shown when new WordPress minor release is available; warns for a major release.

cron-count – Checks the count of cron jobs and displays an error when there is an excess of 50 total cron jobs registered.

cron-duplicates – Checks the count of duplicate cron jobs and displays an error when there is an excess of 10 duplicate cron jobs registered.

option-blog-public – Verifies if the website is publicly available by checking the value of the blog_public option.

plugin-active-count – Shows a warning when there are more than 80 plugins activated.

plugin-deactivated – Warns when more than 40% of plugins are deactivated.

plugin-update – Shows a warning when there are plugin updates available.

theme-update – Warns when there are theme updates available.

php-in-upload – Shows a warning when a PHP file is present in the Uploads folder.

language-update – Checks if there is a new version of the installed language.

If you prefer to run only one or a few of the checks above, you can just specify them instead of using the –all option. You can check how to do that in the two examples below:

wp doctor check autoload-options-size


wp doctor check autoload-options-size core-verify-checksums

Installation and usage of WP Profile

WP Profile is a tool developed to help in diagnosing problems with slow WordPress websites. The main idea of the extension is to split the loading process into stages and then give the ability to track each one of them. It provides information about timings, callbacks, and locations. To use the tool, you should first install it. You can do that by running the command below in your WordPress website’s document root:

wp package install wp-cli/profile-command

After the tool is successfully installed, you can start using it with the wp profile command.

To check all available options of the command, use:

wp profile --help

The subcommands of wp profile are:

  • eval – Profile arbitrary code execution. Arbitrary code execution (ACE) is used to describe an attacker’s ability to execute arbitrary commands or code on a target website.
  • eval file – Profile execution of an arbitrary file.
  • hook – Profile key metrics for WordPress hooks (actions and filters).
  • stage – Profile each stage of the WordPress load process (bootstrap, main_query, template).

To investigate the slow loading of a website, start with using the stage subcommand as shown below:

wp profile stage

You should run that in your website’s document root. The output is a table showing information about the loading process of your website. The most important columns of that table are:

  • Stage – The stages are 3 – bootstrap, main_query, template. In a few simple words – bootstrap is where WordPress is setting itself up, loading plugins and the main theme, and firing the init hook , main_query is how WordPress deals with requests and process them in its queries, template is where WordPress determines which theme template to render based on the main query, and renders it.
  • Time – Shows the time that each stage needs to load.
  • Cache ratio – Shows the percentage of caching on the different stages.

Check which of the stages take the most time to load (e.g. bootstrap) and run the command below:

wp profile stage bootstrap --spotlight

Use —spotlight to filter the zero values.

What usually slows down WordPress instances are not the core functionalities, but its plugins. Track them using:

wp profile hook plugins_loaded --fields=callback,time,location --spotlight

The output of this command will provide you with information about the loading times of different plugins.

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.

You can also create a backup of the WordPress database via WP-CLI, by using the following command:

username@servername [~/WordPress/location]# wp db export
Success: Exported to 'username_wp123-3150ba8.sql'.

If you decide to change the primary domain for the WordPress web site you can easily update the corresponding URL options:

wp option update home https://newdomain.com
wp option update siteurl https://newdomain.com

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

Check out our Handy WP-CLI & SSH Tricks for Website Management Webinar ( 40m )

Tutorial Menu

Share This Article