Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 68 ยท Performance, Tools and Scaling

WP-CLI

Learn WP-CLI: install it, manage core, plugins, themes, posts and options, export databases, run search-replace safely and write your own custom commands.

WP-CLI is the official command-line interface for WordPress. Anything you can click in the dashboard, and plenty you cannot, is a short command: install WordPress, update every plugin, create 500 test posts, export the database, replace a domain name everywhere, or clear a cache. Commands are fast, scriptable and repeatable, which makes WP-CLI the backbone of deployment scripts, staging refreshes and server maintenance.

This lesson tours the commands you will use most, shows how to write safe scripts, and then builds your own command with WP_CLI::add_command(). WP-CLI needs a real server with PHP and a database, so the shell commands and WordPress classes below are read-only. The runnable examples are plain-PHP stand-ins that show how argument parsing and command dispatch work.

Install and first run

WP-CLI is a single PHP archive (a .phar file). Download it, make it executable and put it on your path:

Terminal
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

wp --info

Many hosts and local tools (Local, Herd, wp-env, Docker images) include it already. You run wp from inside a WordPress folder, or point at one with --path:

Terminal
cd /var/www/example.com
wp core version

wp --path=/var/www/example.com core version

A few global parameters work with every command:

Parameter Meaning
--path=<dir> The WordPress directory
--url=<url> Which site to act on (essential for multisite)
--user=<id> Run as this user, by ID, login or email (needed for some commands)
--skip-plugins, --skip-themes Do not load them: great when a broken plugin crashes WordPress
--allow-root Permit running as root (avoid; run as the site's user)
--quiet, --debug Less or more output

Use wp help <command> to see every option and examples for any command. Tab completion is available if you install the completion script.

Install WordPress from scratch

The whole local setup from Setting Up a Local WordPress Site becomes five commands:

Terminal
wp core download
wp config create --dbname=wp_example --dbuser=wp --dbpass=secret --dbhost=127.0.0.1
wp db create
wp core install \
  --url=http://example.test \
  --title="Example Site" \
  --admin_user=admin_ana \
  --admin_email=ana@example.test \
  --prompt=admin_password

The --prompt option asks for the password instead of leaving it in your shell history. Store real credentials in a password manager, not in scripts.

Core, plugins and themes

Terminal
# Core
wp core check-update
wp core update
wp core verify-checksums          # compare core files with the official release

# Plugins
wp plugin list
wp plugin install query-monitor --activate
wp plugin update --all
wp plugin deactivate some-plugin
wp plugin delete some-plugin

# Themes
wp theme list
wp theme install twentytwentyfive --activate
wp theme activate my-block-theme

wp plugin deactivate --all is a classic debugging step when a site is broken, as described in Debugging WordPress, and --skip-plugins lets WP-CLI run even when a plugin causes a fatal error.

Content: posts, users and options

Terminal
# Create a post and print only its ID
wp post create --post_title="Hello CLI" --post_status=publish \
  --post_content="Created from the command line." --porcelain

# Query posts
wp post list --post_type=page --fields=ID,post_title,post_status --format=table
wp post list --post_status=draft --format=ids

# Bulk edit
wp post delete $(wp post list --post_status=trash --format=ids) --force

# Users
wp user create ben ben@example.test --role=editor
wp user list --fields=ID,user_login,roles --format=csv

# Options (the Options API from the command line)
wp option get blogname
wp option update blogdescription "Notes from the terminal"
wp option list --search="myplugin_*"

The --format flag (table, csv, json, ids, count, yaml) makes output friendly to both people and scripts. Always use --porcelain, --format=ids or --format=json when a script has to parse a result, rather than scraping a table. Meta commands such as wp post meta get/update and wp term create mirror the PHP functions you met in Custom Fields and Post Meta and the taxonomy lessons.

Generating test data is easy: wp post generate --count=50 creates dummy posts and wp user generate --count=10 creates users. Do this only on a development copy.

Database commands

Terminal
wp db export backup-2025-06-01.sql      # dump the database
wp db import backup-2025-06-01.sql      # load a dump
wp db query "SELECT COUNT(*) FROM wp_posts WHERE post_status='publish'"
wp db check
wp db optimize
wp db size --tables

wp db export is the first step before any risky operation. The result goes into a plain SQL file, and the security lesson on backups explains why you should also keep a copy off the server.

Search-replace

When you move a site to a new domain, the old URL is stored in many places, including inside serialized PHP arrays (options, widget settings, page builder data). A plain SQL REPLACE() corrupts serialized strings, because they include string lengths. wp search-replace understands serialization and updates the lengths for you.

Terminal
# See what would change, without writing anything.
wp search-replace 'http://old.example.test' 'https://example.com' --dry-run

# Apply it (back up first!). --skip-columns=guid keeps post GUIDs intact.
wp search-replace 'http://old.example.test' 'https://example.com' \
  --all-tables --skip-columns=guid

Always run --dry-run first and read the table counts. Replacing a short string such as dev would match far more than you intended.

Running PHP: eval and scripts

wp eval runs PHP with WordPress fully loaded; wp eval-file runs a script file. They are excellent for one-off fixes and migrations:

Terminal
wp eval 'echo get_bloginfo( "name" ), PHP_EOL;'
wp eval 'echo wp_count_posts()->publish, PHP_EOL;'
wp eval-file scripts/backfill-meta.php --user=1

Long jobs should work in batches and print progress, so a timeout or crash does not lose everything. Use --skip-plugins for scripts that do not need plugin code, which makes them faster and safer. Remember that anything you do in wp eval runs with full privileges: there is no capability check unless you add one (see Users, Roles and Capabilities, where --user sets the acting user).

Cron, cache and rewrites

Terminal
wp cron event list
wp cron event run --due-now        # what a system cron job calls
wp cache flush                     # clear the object cache
wp transient delete --all
wp rewrite flush                   # regenerate permalink rules
wp language core update

These are exactly the commands behind the system-cron advice in Caching and WP-Cron. A crontab line such as */5 * * * * cd /var/www/example.com && wp cron event run --due-now replaces the visit-triggered scheduler.

Writing your own commands

Every command in WP-CLI is registered by name. Your plugin can add commands with WP_CLI::add_command(), usually inside a guard so the code only loads in the CLI:

PHP
<?php
if ( defined( 'WP_CLI' ) && WP_CLI ) {
    WP_CLI::add_command( 'greeter', 'MyPlugin_Greeter_Command' );
}

/**
 * Greets people and counts things.
 */
class MyPlugin_Greeter_Command {

    /**
     * Prints a greeting.
     *
     * ## OPTIONS
     *
     * <name>
     * : Who to greet.
     *
     * [--shout]
     * : Print in upper case.
     *
     * [--times=<n>]
     * : How many times to print it.
     * ---
     * default: 1
     * ---
     *
     * ## EXAMPLES
     *
     *     wp greeter hello Ana --times=2 --shout
     *
     * @when after_wp_load
     */
    public function hello( array $args, array $assoc_args ): void {
        list( $name ) = $args;
        $times = (int) \WP_CLI\Utils\get_flag_value( $assoc_args, 'times', 1 );
        $text  = "Hello, {$name}!";

        if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'shout', false ) ) {
            $text = strtoupper( $text );
        }

        for ( $i = 0; $i < $times; $i++ ) {
            WP_CLI::line( $text );
        }

        WP_CLI::success( 'Done.' );
    }
}

Run it with wp greeter hello Ana --times=2 --shout. A few things to notice:

  • The class name maps to the command greeter; each public method is a subcommand. A class with only an __invoke() method becomes a single command.
  • WP-CLI reads the docblock to learn the arguments: <name> is required positional, [--shout] an optional flag, [--times=<n>] an option with a default. Invalid usage is rejected for you, and wp help greeter hello prints the documentation.
  • Positional arguments arrive in $args; flags and options arrive in $assoc_args.
  • Output goes through WP_CLI::line(), WP_CLI::log(), WP_CLI::success(), WP_CLI::warning() and WP_CLI::error() (which prints and exits with a failing status code, so scripts can detect it). Use WP_CLI\Utils\format_items() for tables, and WP_CLI\Utils\make_progress_bar() for long loops.
flowchart LR
    A["wp greeter hello Ana --shout"] --> B["Parse words,<br/>flags and options"]
    B --> C["Find command<br/>'greeter' then 'hello'"]
    C --> D["Validate against<br/>docblock synopsis"]
    D --> E["Call method with<br/>$args and $assoc_args"]
    E --> F["Exit status<br/>0 or non-zero"]

WP-CLI turns a line of text into a method call and an exit status.

The first stand-in shows the parsing half: it splits a command line into positional words, --flag and --key=value options, then dispatches through a command table. Real WP-CLI is far more capable (documented synopses, validation, global parameters), but the shape is the same.

PHP A tiny command dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The exit status is the part scripts rely on: 0 means success and anything else means failure, so a deployment script can stop on the first error.

Output formats

A good command lets the caller choose the output format, so humans get a table and scripts get JSON. The second stand-in mimics how WP-CLI's --format works over the same rows.

PHP One result set, several --format values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Habits for safe scripting

  • Back up first: wp db export before anything that writes in bulk.
  • Dry-run first where a command offers it (search-replace --dry-run).
  • Check exit codes: use set -e at the top of Bash scripts so they stop on the first failure.
  • Parse machine-readable output (--format=json, --porcelain), not tables.
  • Run as the site's user, not root, and pass --url explicitly on multisite installs (see Multisite Overview).
  • Keep long-running commands out of the web request: they belong in WP-CLI, not in admin-ajax.php.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use wp search-replace instead of a plain SQL REPLACE() when changing a site's domain?

    Serialized PHP data stores string lengths. A raw REPLACE() changes the text but not the length, corrupting the value. search-replace rewrites the serialized data correctly.
  2. 2. How do you see what a risky search-replace would change without writing anything?

    --dry-run prints the number of replacements per table and column but changes nothing, so you can review it first.
  3. 3. Which flag lets WP-CLI run when a broken plugin is causing a fatal error?

    --skip-plugins prevents plugin files from loading, which lets you deactivate or update the offender from the command line.
  4. 4. In a custom command class, where do the flags and key=value options arrive?

    Positional arguments are passed in the first array ($args) and named flags and options in the second ($assoc_args). The docblock only describes them.
  5. 5. A deployment script runs wp commands. How should it detect that one failed?

    WP-CLI exits with a non-zero status on failure (WP_CLI::error() does this). Scripts should rely on that, not on matching output text.

Summary

  • WP-CLI runs WordPress tasks from the terminal: install, update, content, database, cache and cron commands, all scriptable.
  • Use --path, --url and --user to choose the site and acting user, and --skip-plugins to work around broken plugins.
  • wp search-replace is serialization-aware; always back up and use --dry-run first.
  • wp eval and wp eval-file run PHP with WordPress loaded, with full privileges.
  • Custom commands register with WP_CLI::add_command(), use docblocks to declare arguments, and report success or failure with output helpers and exit codes.
  • Prefer machine-readable formats and exit codes in scripts.

Next, see how one WordPress install can serve many sites: Multisite Overview.