References

References

Argument Syntax

WP-CLI commands use a standardized syntax to describe their arguments and options. Understanding this syntax will help you use commands correctly and avoid confusion.

Syntax Conventions

The command synopsis uses specific formatting to indicate whether arguments are required or optional, and what type of values they accept.

Required Arguments

Arguments without square brackets are required and must be provided:

Optional Arguments

Arguments enclosed in square brackets [ ] are optional:

Boolean Flags

Boolean flags are switches that enable or disable a feature:

Associative Arguments

Some commands accept arbitrary key-value pairs:

Repeatable Arguments

Arguments that can be provided multiple times:

Variadic Arguments

Arguments that accept multiple values:

Value Placeholders

The text inside angle brackets describes what kind of value is expected:

Common Patterns

Required Database Connection

Many commands require database connection details:

--dbname=<dbname> --dbuser=<dbuser> [--dbpass=<dbpass>] [--dbhost=<dbhost>]

Format Options

Commands that output data often accept a format option:

[--format=<format>]

Common formats include: table, csv, json, yaml, count

Fields and Filtering

Commands that work with multiple fields:

[--fields=<fields>] [--field=<field>]

Examples

Here are practical examples showing different syntax types:

# Required arguments (no brackets)
wp config create --dbname=mydb --dbuser=root

# Optional arguments with defaults
wp config create --dbname=mydb --dbuser=root --dbhost=localhost

# Boolean flags
wp plugin install hello-dolly --activate --force

# Negated boolean flags
wp plugin list --no-color

# Associative arguments
wp cron event schedule my_hook --foo=bar --baz=qux

# Multiple values
wp plugin install plugin1 plugin2 plugin3

# Optional fields with specific format options
wp post list --format=json --fields=ID,post_title,post_date

Tips

Behat Steps

WP-CLI makes use of a Behat-based testing framework and provides a set of custom step definitions to write feature tests.

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given

When

Then

Config

WP-CLI has a series of global parameters (e.g. --path=<path> and --user=<user>) which work with all commands. They are called global parameters because they affect how WP-CLI interacts with WordPress, and have the same behavior across all commands.

# `--user=<user>` sets request to a specific WordPress user
$ wp --user=wpcli eval 'echo wp_get_current_user()->user_email;'
wpcli@example.com

For repeated usage, WP-CLI can also read options from a YAML configuration file (e.g. wp-cli.yml). WP-CLI automatically discovers configuration files on the filesystem based on rules defined below. These configuration files enable specifying default values for both global parameters and subcommand-specific arguments.

# WordPress develop includes a `wp-cli.yml` to enable easy use of WP-CLI
$ pwd
/srv/www/wordpress-develop.dev
$ cat wp-cli.yml
path: src/

Arguments are interpreted following an order of precedence, from highest priority to lowest:

  1. Command-line arguments.
  2. wp-cli.local.yml file inside the current working directory (or upwards).
  3. wp-cli.yml file inside the current working directory (or upwards).
  4. ~/.wp-cli/config.yml file (path can be changed by setting the WP_CLI_CONFIG_PATH environment variable).
  5. WP-CLI defaults.

Global parameters

The table below lists the available arguments (specified on the command-line) and options (specified in the configuration file).

Description Argument Option
Path to the WordPress files.
Default value: null
--path=<path> path: <path>
Perform operation against a remote server over SSH.
Default value: null
--ssh=[<user>@]<host>[:<port>][<path>] ssh: [<user>@]<host>[:<port>][<path>]
Perform operation against a remote WordPress install over HTTP.
Default value: null
--http=<http> http: <http>
Pretend request came from given URL. In multisite, this argument is how the target site is specified.
Default value: null
--url=<url> url: <url>
Set the WordPress user.
Default value: null
--user=<id|login|email> user: <id|login|email>
Skip loading all or some plugins. Note: mu-plugins are still loaded.
Default value: ""
--skip-plugins[=<plugin>] skip-plugins: <list>
Skip loading all or some themes.
Default value: ""
--skip-themes[=<theme>] skip-themes: <list>
Skip loading all installed packages.
Default value: false
--skip-packages skip-packages: <bool>
Load PHP file before running the command (may be used more than once).
Default value: []
--require=<path> require: <path>
Execute PHP code before running the command (may be used more than once).
Default value: []
--exec=<php-code> exec: <php-code>
Load WordPress in a given context.
Default value: auto
--context[=<context>] context: <context>
(Sub)commands to disable.
Default value: []
Not available as a flag disabled_commands: <list>
Whether to colorize the output.
Default value: "auto"
--[no-]color color: <bool>
Show all PHP errors; add verbosity to WP-CLI bootstrap.
Default value: false
--debug[=<group>] debug: <group>
Prompt the user to enter values for all command arguments, or a subset specified as comma-separated values.
Default value: false
--prompt[=<assoc>] Not available as an option
Suppress informational messages.
Default value: false
--quiet quiet: <bool>
List of Apache Modules that are to be reported as loaded.
Default value: []
Not available as a flag apache_modules: <list>

Config files

WP-CLI can automatically discover and read options from a few configuration file types (when present):

  1. wp-cli.local.yml file inside the current working directory (or upwards).
  2. wp-cli.yml file inside the current working directory (or upwards).
  3. ~/.wp-cli/config.yml file (path can be changed by setting the WP_CLI_CONFIG_PATH environment variable).

Besides the global parameters described above, configuration files can also contain defaults for any subcommand, as well as aliases to one or more WordPress installs.

Here's an annotated example wp-cli.yml file:

# Global parameter defaults
path: wp-core
url: http://example.com
user: admin
color: false
disabled_commands:
  - db drop
  - plugin install
require:
  - path-to/command.php

# Subcommand defaults (e.g. `wp config create`)
config create:
	dbuser: root
	dbpass: 
	extra-php: |
		define( 'WP_DEBUG', true );
		define( 'WP_POST_REVISIONS', 50 );

# Aliases to other WordPress installs (e.g. `wp @staging rewrite flush`)
# An alias can include 'user', 'url', 'path', 'ssh', or 'http'
@staging:
	ssh: wpcli@staging.wp-cli.org
	user: wpcli
	path: /srv/www/staging.wp-cli.org
@production:
	ssh: wpcli@wp-cli.org:2222
	user: wpcli
	path: /srv/www/wp-cli.org

# Aliases can reference other aliases to create alias groups
# Alias groups can be nested
@both:
 - @staging
 - @production

# '_' is a special value denoting configuration options for this wp-cli.yml
_:
	# Merge subcommand defaults from the upstream config.yml, instead of overriding
	merge: true
	# Inherit configuration from an arbitrary YAML file
	inherit: prod.yml

Remote (SSH) configuration

Using the ssh option, WP-CLI can be configured to run on a remote system rather than the current system. Along with the SSH protocol, WP-CLI also supports connecting to Docker containers (including docker-compose) and Vagrant VMs.

The connection type can be passed via the scheme of the --ssh parameter or ssh option.

Supported types are:

All connection types support an optional path suffix to specify a directory to cd to before running WP-CLI; path is a full system path starting with either / or ~. (If WP_CLI_SSH_PRE_CMD is specified, cd is run after this pre-command.)

The SSH connection type also supports two advanced connection configuration options, which must be specified via an alias in the YAML configuration:

See the documentation about running WP-CLI commands remotely for more information.

Context configuration

In WP-CLI v2.6.0, a new global flag --context=<context> was added which allows users to select the WordPress context in which WP-CLI is supposed to execute its command(s).

One of the main goals is to allow WP-CLI to run updates on premium plugins and themes without requiring any special setup. From our initial testing, this allows a large range of popular premium extensions to just work™ with WP-CLI in terms of their update procedures.

Possible values for this flag:

By default, the --context flag was set to cli in the initial release (v2.6.0). In WP-CLI v2.7.0 and later versions, the default was changed to auto. This gradual deployment allowed hosters and site owners to run tests on v2.6.0 by manually setting the context before the default behavior was changed.

If you are still using WP-CLI v2.6.0 but you want to use the default of --context=auto, you can do so by adding the necessary context: auto line to your global wp-cli.yml configuration file. Feel free to check the documentation on WP-CLI configuration files if this is new to you.

Environment variables

WP-CLI's behavior can be changed at runtime through the use of environment variables:

To set an environment variable on demand, simply place the environment variable definition before the WP-CLI command you mean to run.

# Use vim to edit a post
$ EDITOR=vim wp post edit 1

To set the same environment variable value for every shell session, you’ll need to include the environment variable definition in your ~/.bashrc or ~/.zshrc file

# Always use vim to edit a post
export EDITOR=vim

Documentation Standards

To promote similarity and consistency between WP-CLI commands, we've produced these documentation standards we'd encourage you to follow. Commonality is a key component of usability, because it reduces the mental overhead required when switching between commands.

Pull requests against the WP-CLI project are reviewed for these standards. Please follow these standards for your custom commands as well.

Command annotation

Here's an example of the PHPdoc annotating the wp cron event schedule command:

/**
 * Schedule a new cron event.
 *
 * ## OPTIONS
 *
 * <hook>
 * : The hook name.
 *
 * [<next-run>]
 * : A Unix timestamp or an English textual datetime description compatible with `strtotime()`. Defaults to now.
 *
 * [<recurrence>]
 * : How often the event should recur. See `wp cron schedule list` for available schedule names. Defaults to no recurrence.
 *
 * [--<field>=<value>]
 * : Associative args for the event.
 *
 * ## EXAMPLES
 *
 *     # Schedule a new cron event.
 *     $ wp cron event schedule cron_test
 *     Success: Scheduled event with hook 'cron_test' for 2016-05-31 10:19:16 GMT.
 *
 *     # Schedule new cron event with hourly recurrence.
 *     $ wp cron event schedule cron_test now hourly
 *     Success: Scheduled event with hook 'cron_test' for 2016-05-31 10:20:32 GMT.
 *
 *     # Schedule new cron event and pass associative arguments.
 *     $ wp cron event schedule cron_test '+1 hour' --foo=1 --bar=2
 *     Success: Scheduled event with hook 'cron_test' for 2016-05-31 11:21:35 GMT.
 */

To break the example down piece by piece:

For more details on how WP-CLI understands the PHPdoc, please see the commands cookbook.

Class annotation

For classes representing a collection of subcommands, we'd encourage you to use class-level annotation to provide an introduction to the collection.

/**
 * Manage options.
 *
 * ## EXAMPLES
 *
 *     # Get site URL.
 *     $ wp option get siteurl
 *     http://example.com
 *
 *     # Add option.
 *     $ wp option add my_option foobar
 *     Success: Added 'my_option' option.
 *
 *     # Update option.
 *     $ wp option update my_option '{"foo": "bar"}' --format=json
 *     Success: Updated 'my_option' option.
 *
 *     # Delete option.
 *     $ wp option delete my_option
 *     Success: Deleted 'my_option' option.
 */

Messages within command execution

$ wp theme activate twentysixteen
Success: Switched to 'Twenty Sixteen' theme.

Command parameter description

If there is a set of allowed values for a command parameter, we have set special format (mostly similar to YAML) for default value and available options.

[--format=<format>]
: Render output in a particular format.
---
default: table
options:
  - table
  - csv
  - json
  - count
  - yaml
---

Exit Codes

WP-CLI follows widely-adopted Unix conventions for exit codes: 0 signals success (the command’s primary condition was satisfied), while non-zero values signal that the primary condition was not satisfied. This can represent either an operational error (the command could not perform the requested operation) or an expected negative result that calling scripts are intended to test for (for example, “not installed”). Scripts that call WP-CLI commands can inspect the exit code to determine whether to continue, retry, or abort.

Standard exit codes

Exit code Meaning
0 Command completed successfully. The requested operation was performed as expected.
1 Command failed. WP-CLI could not perform the operation as expected (e.g. invalid arguments, WordPress not found, a fatal error was encountered).

WP_CLI::error() (doc) is the conventional way to report a failure and exit with code 1.

WP_CLI::halt() (doc) can be used to exit with a specific non-zero code when the command needs to communicate a particular outcome to the calling script.

Exit codes for boolean-result commands

Some commands are designed to communicate a binary result directly through the exit code rather than through output. These commands still use the standard 0/1 codes, but 1 means "condition not met" rather than "operational error". For example:

Use exit code 1 to signal "condition not met" (rather than an error) when:

  1. The command result is binary (pass/fail, found/not-found) and is intended to be tested directly in a shell conditional.
  2. The intent is explicitly documented so script authors know the exit code carries a result meaning, not an error meaning.

Do not return a non-zero exit code for conditions that are informational rather than a definitive result (e.g. a list command that finds no items is still a successful operation — it returned an empty list).

Using exit codes in scripts

Because WP-CLI uses standard exit codes, you can use WP-CLI commands directly in shell conditionals:

# Check if a plugin is installed before trying to activate it
if wp plugin is-installed my-plugin; then
    wp plugin activate my-plugin
else
    echo "Plugin not installed"
    exit 1
fi

You can also inspect $? after any WP-CLI command to check whether it succeeded:

wp core update
if [ "$?" -ne 0 ]; then
    echo "Update failed"
fi

Given /^&quot;([^&quot;]+)&quot; replaced with &quot;([^&quot;]+)&quot; in the ([^\s]+) file$/

Search and replace a string in a file using regex.


Usage

Scenario: My example scenario
  Given "Foo" replaced with "Bar" in the readme.html file
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^a downloaded Phar with (?:the same version|version &quot;([^&quot;]+)&quot;)$/

Download a specific WP-CLI Phar version from GitHub.


Usage

Scenario: My example scenario
  Given an empty directory
  And a downloaded Phar with version "2.11.0"

Scenario: My other scenario
  Given an empty directory
  And a downloaded Phar with the same version

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^a new Phar with (?:the same version|version &quot;([^&quot;]+)&quot;)$/

Build a new WP-CLI Phar file with a given version.


Usage

Scenario: My example scenario
  Given an empty directory
  And a new Phar with version "2.11.0"

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^a WP multisite (subdirectory|subdomain)?\s?(install|installation)$/

Installs WordPress Multisite.


Usage

Supports either subdirectory or subdomain installation.

Scenario: My example scenario
  Given a WP multisite subdomain installation
  ...

Scenario: My other scenario
  Given a WP subdirectory install
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^a WP( [^\s]+)? install(?:ation)? in ['&quot;]?([^'&quot;]+)['&quot;]?$/

Installs WordPress in a given directory.


Usage

Scenario: My example scenario
  Given a WP installation in 'foo'
  ...

Scenario: My other scenario
  Given a WP install in 'bar'
  ...

Scenario: My version-specific scenario
  Given a WP 6.4.2 installation in 'subdir'
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^a WP( \d[^\s]+)? install(?:ation)?$/

Installs WordPress.


Usage

Scenario: My example scenario
  Given a WP installation
  ...

Scenario: My other scenario
  Given a WP install
  ...

Scenario: My version-specific scenario
  Given a WP 6.4.2 installation
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^an? (&quot;[^&quot;]+&quot;|[^\s]+) (file|cache file):$/

Creates a file with the given contents.


Usage

The file can be created either in the current working directory or in the cache directory.

Scenario: My example scenario
  Given a wp-cli.yml file:
    """
    @foo:
      path: foo
      user: admin
    """

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^an? (empty|non-existent) ([^\s]+) directory$/

Creates or deletes a specific directory.


Usage

Scenario: My example scenario
  Given an empty foo-plugin directory
  And a non-existent bar-plugin directory
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^save (STDOUT|STDERR) ([\'].+[^\'])?\s?as \{(\w+)\}$/

Store STDOUT or STDERR contents in a variable.


Usage

Scenario: My example scenario
  When I run `wp package path`
  Then save STDOUT as {PACKAGE_PATH}

Scenario: My other scenario
  When I run `wp core download`
  Then save STDOUT 'Downloading WordPress ([\d\.]+)' as {VERSION}

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^save the (.+) file ([\'].+[^\'])?as \{(\w+)\}$/

Stores the contents of the given file in a variable.


Usage

Scenario: My example scenario
  Given a WP installation with Composer
  And save the {RUN_DIR}/composer.json file as {COMPOSER_JSON}

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given /^that HTTP requests to (.*?) will respond with:$/

Mock HTTP requests to a given URL.


Usage

Scenario: My example scenario
  Given that HTTP requests to https://api.github.com/repos/wp-cli/wp-cli/releases?per_page=100 will respond with:
    """
    HTTP/1.1 200
    Content-Type: application/json

    { "foo": "bar" }
    """

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given a custom wp-content directory

Configure a custom wp-content directory.


Usage

Defines the WP_CONTENT_DIR, WP_PLUGIN_DIR, and WPMU_PLUGIN_DIR constants.

Scenario: My example scenario
  Given a WP install
  And a custom wp-content directory

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given a database

Creates an empty database.


Usage

Has no effect when tests run with SQLite.

Scenario: My example scenario
  Given a database
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given a dependency on current wp-cli

Add wp-cli/wp-cli as a Composer dependency.


Usage

Scenario: My example scenario
  Given a WP installation with Composer
  And a dependency on current wp-cli

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given a misconfigured WP_CONTENT_DIR constant directory

Modify wp-config.php to set WP_CONTENT_DIR to an empty string.


Usage

Scenario: My example scenario
  Given a WP install
  And a misconfigured WP_CONTENT_DIR constant directory

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given a PHP built-in web server

Start a PHP built-in web server in the current directory.


Usage

Scenario: My example scenario
  Given a WP installation
  And a PHP built-in web server

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given a PHP built-in web server to serve :subdir

Start a PHP built-in web server in the given subdirectory.


Usage

Scenario: My example scenario
  Given a WP installation
  And a PHP built-in web server to serve 'WordPress'

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given a WP install(ation) with Composer

Installs WordPress with Composer.


Usage

Scenario: My example scenario
  Given a WP installation with Composer
  ...

Scenario: My other scenario
  Given a WP install with Composer
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given a WP install(ation) with Composer and a custom vendor directory :vendor_directory

Installs WordPress with Composer and a custom vendor directory.


Usage

Scenario: My example scenario
  Given a WP installation with Composer and a custom vendor directory 'vendor-custom'
  ...

Scenario: My other scenario
  Given a WP install with Composer with Composer and a custom vendor directory 'vendor-custom'
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given an empty cache

Clears the WP-CLI cache directory.


Usage

Scenario: My example scenario
  Given an empty cache
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given an empty directory

Creates an empty directory.


Usage

Scenario: My example scenario
  Given an empty directory
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given download:

Download multiple files into the given destinations.


Usage

Scenario: My example scenario
  Given download:
    | path                | url                                   |
    | {CACHE_DIR}/foo.jpg | https://example.com/foo.jpg           |
    | {CACHE_DIR}/bar.png | https://example.com/another-image.png |

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given these installed and active plugins:

Installs and activates one or more plugins.


Usage

Scenario: My example scenario
  Given a WP installation
  And these installed and active plugins:
    """
    akismet
    wordpress-importer
    """

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given WP files

Download WordPress files without installing.


Usage

Scenario: My example scenario
  Given an empty directory
  And WP files

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Given wp-config.php

Create a wp-config.php file using wp config create.


Usage

Scenario: My example scenario
  Given an empty directory
  And WP files
  And wp-config.php

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Hosting Companies

The following is a list of hosting companies that have WP-CLI installed by default for their customers, i.e. when they first SSH into their server, the wp command is already available.

In alphabetical order:

The following is a list of hosting companies that use WP-CLI, whereby their customers can write and request the running of standard and custom WP-CLI commands:

Internal API

WP-CLI includes a number of utilities which are considered stable and meant to be used by commands.

This also means functions and methods not listed here are considered part of the private API. They may change or disappear at any time.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Registration

Output

Input

Execution

System

Misc

Shell Friends

As you advance upon your use of WP-CLI, you'll find that a little bit of command line knowledge can have a huge impact on your workflow. Here are some of our favorite shell helper utilities.

You Should Know

Search through your bash history

Did you know that every command you run on your shell is saved to history? Search through your history with CTRL + R:

$ wp core download --version=nightly --force
bck-i-search: wp

When 'bck-i-search' appears, your keystrokes will search against commands saved in your bash history. Hit return to run the current selection.

Or another way to search history is grepping the output from the history command like:

$ history | grep wp

Any of the commands found in that list can be re-executed by bang-number, so for example if the output says your desired command is #218, you just do !218

Combine WP-CLI commands

In many cases, it can be extremely powerful to be able to pass the results of one command to another. Composability is a key philosophy of WP-CLI, and there are two common approaches for composing commands.

Command substitution passes the output of one command to another command, without any transformation to the output.

wp post list only lists posts; it doesn't perform any operation on them. In this example, the command lists page ids as space-separated values.

$ wp post list --post_type='page' --format=ids
1164 1186

Combining wp post list with wp post delete lets you easily delete all posts. In this example, $() lets us pass the space-separated page ids to wp post delete.

$ wp post delete $(wp post list --post_type='page' --format=ids)
Success: Trashed post 1164.
Success: Trashed post 1186.

If you need a bit more flexibility, xargs lets you pass the output of one command to another command, while performing minor transformation on the output.

You may want to assign all editor capabilities to the author role. However, wp cap list lists capabilities separated by newlines, and wp cap add only accepts space-separated capabilities. Enter, xargs, whose default behavior is to split newline output into a space-separated list. Note the | shell operator, which passes the results of wp cap list to xargs. Without |, you'll see a WP-CLI error.

$ wp cap list 'editor' | xargs wp cap add 'author'
Success: Added 24 capabilities to 'author' role.

wp user generate only generates users; it doesn't perform supplemental operations. In this example, wp user generate passes user ids to xargs, which splits the space-separated ids into a list and calls wp user meta add for each.

$ wp user generate --count=5 --format=ids | xargs -0 -d ' ' -I % wp user meta add % foo bar
Success: Added custom field.
Success: Added custom field.
Success: Added custom field.
Success: Added custom field.
Success: Added custom field.

Define aliases, short macros to common commands

If you find yourself running the same commands quite often, you can define aliases to them for easier access.

Run all three status check commands with one check-all alias. In this example, running alias creates a check-all alias for the current shell session. Save the same statement to your ~/.bashrc or ~/.zshrc to always have it available.

$ alias check-all='wp core check-update && wp plugin list --update=available && wp theme list --update=available'
$ check-all
+-----------------+-------------+-----------------------------------------------------------+
| version         | update_type | package_url                                               |
+-----------------+-------------+-----------------------------------------------------------+
| 4.7-beta4-39322 | minor       | https://wordpress.org/nightly-builds/wordpress-latest.zip |
+-----------------+-------------+-----------------------------------------------------------+
+-------------------------+----------+-----------+--------------+
| name                    | status   | update    | version      |
+-------------------------+----------+-----------+--------------+
| akismet                 | inactive | available | 3.1.8        |
| co-authors-plus         | inactive | available | 3.1.1        |
| wp-redis                | inactive | available | 0.2.2        |
| rest-api                | active   | available | 2.0-beta13.1 |
| wp-api-oauth1           | inactive | available | 0.2          |
+-------------------------+----------+-----------+--------------+
+----------------------+----------+-----------+---------+
| name                 | status   | update    | version |
+----------------------+----------+-----------+---------+
| p2                   | inactive | available | 1.4.2   |
+----------------------+----------+-----------+---------+

Save command output

WP-CLI commands send output to both STDOUT and STDERR, depending on the nature of the message. You may not notice there are two destinations, because WP-CLI renders both inside your shell. However, if you want to capture your output to a file, the distinction matters.

Simply using > will capture STDOUT from the command to a file.

$ wp import wordpress.wxr --authors=create > import.log

Redirect STDERR to STDOUT with 2>&1, and then capture STDOUT to a log file.

$ wp import wordpress.wxr --authors=create > import.log 2>&1

When you're capturing output to a file, you won't see the output in your current shell session. However, you can open a second shell session and run tail -f <file> to see the output as it's added to the file.

Alternatively, you can use tee that writes to both standard output and files. You only have to pipe the output to the command and specify the file name.

$ wp import wordpress.wxr --authors=create | tee import.log

This will display the output in the current shell screen and also write it to the log file.

Note that if the file already exists, it will be overwritten. If you want to append the output to the file, use the -a option.

$ wp import wordpress.wxr --authors=create | tee -a import.log

Snippets

Are you an expert in bash or zsh? Share your tips here.

Take a look at the plugin changelog

wget -qO- http://api.wordpress.org/plugins/info/1.0/akismet|php -r '$seri=unserialize(stream_get_contents(STDIN)); echo $seri->sections["changelog"];'|elinks -force-html

Explanation

Start wp-cli with ABSPATH in the current dir and under the current dir's owner

#!/bin/bash

sudo -u $(stat . -c %U) -- wp --path="$PWD" "$@"

Explanation

The stat command returns the owner of the current directory, WordPress root.

Install and Configure WordPress with WP-CLI

wp_install () 
{ 
    wp core download --path=$1;
    cd $1;
    read -p 'name the database:' dbname;
    wp config create --dbname=$dbname --dbuser=root --dbpass=awoods --dbhost=localhost;
    wp db create;
    wp core install --prompt
}

$ source ~/.bashrc
$ wp_install new-site

Explanation

Add this function to your ~/.bashrc are reload your shell (or open a new shell). You'll need to substitute these database credentials with your own. When you need to create a new WordPress site, call this function and specify the name of the directory where you want to create the site. This emulates the web-based install process.

List all image URL-s in posts

wp post list --field=ID|xargs -I % wp post get % --field=post_content|sed -ne 's;.*\(https\?\S\+\(jpe\?g\|png\|gif\)\).*;\1;gp'

Explanation

Create a page from a file and flag it with the file name

wp post create new_page.html --post_type=page --post_title="New Page" --porcelain | xargs -I % wp post meta add % imported_from new_page.html

Explanation

Change to a certain WordPress installation's directory from a menu

#!/bin/bash

WP_TOP_PATH="/home/"
MENU_TEXT="Choose an installation"
GAUGE_TEXT="Searching for WordPress"

declare -a MENU
WPS="$(wp --allow-root find "$WP_TOP_PATH" --field=version_path)"
WP_TOTAL="$(wc -l <<< "$WPS")"
WP_COUNT="0"

while read -r WP; do
    WP_LOCAL="${WP%wp-includes/version.php}"

    NAME="$(cd "$WP_LOCAL"; sudo -u "$(stat . -c %U)" -- wp --no-debug --quiet option get blogname)"
    if [ -z "$NAME" ]; then
        NAME="(unknown)"
    fi
    MENU+=( "$WP_LOCAL" "$NAME" )

    echo "$((++WP_COUNT * 100 / WP_TOTAL))".
done <<< "$WPS" > >(whiptail --gauge "$GAUGE_TEXT" 7 74 0)

WP_LOCAL="$(whiptail --title "WordPress" --menu "$MENU_TEXT"  $((${#MENU[*]} / 2 + 7)) 74 10 "${MENU[@]}" 3>&1 1>&2 2>&3)"

if [ $? -ne 0 ] || [ ! -d "$WP_LOCAL" ]; then
    echo "Cannot find '${WP_LOCAL}'" 1>&2
    exit 100
fi

echo "cd ${WP_LOCAL}"

Explanation

Discard header row from a CSV

By default, --format=csv includes a header row:

$ wp user list --format=csv
ID,user_login,display_name,user_email,user_registered,roles
1,daniel,daniel,daniel@handbuilt.co,"2022-12-21 23:05:16",administrator

If you'd like to discard the header row, tail is pretty helpful:

$ wp user list --format=csv | tail -n +2
1,daniel,daniel,daniel@handbuilt.co,"2022-12-21 23:05:16",administrator

Sort plugins or themes by certain column(s)

Then /^(STDOUT|STDERR) should be a number$/

Expect STDOUT or STDERR to be a numeric value.


Usage

Scenario: My example scenario
  Given a WP installation
  When I run `wp db size --size_format=b`
  Then STDOUT should be a number

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^(STDOUT|STDERR) should be a version string (&lt;|&lt;=|&gt;|&gt;=|==|=|!=|&lt;&gt;) ([+\w.{}-]+)$/

Expect STDOUT or STDERR to be a version string comparing to the given version.


Usage

Scenario: My example scenario
  Given a WP install
  When I run `wp core version
  Then STDOUT should be a version string >= 6.8

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^(STDOUT|STDERR) should be empty$/

Expect STDOUT or STDERR to be empty.


Usage

Scenario: My other scenario
  Given a WP install
  When I run `wp plugin install akismet`
  Then STDERR should be empty

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^(STDOUT|STDERR) should not be a number$/

Expect STDOUT or STDERR to not be a numeric value.


Usage

Scenario: My example scenario
  Given a WP installation
  When I run `wp post list --format=json`
  Then STDOUT should not be a number

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^(STDOUT|STDERR) should not be empty$/

Expect STDOUT or STDERR not to be empty.


Usage

Scenario: My example scenario
  When I run `wp user create examplejane jane@example.com`
  Then STDOUT should not be empty

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^(STDOUT|STDERR) should( not)? match (((\/.+\/)|(#.+#))([a-z]+)?)$/

Match STDOUT or STDERR against a regex.


Usage

Scenario: My example scenario
  When I run `wp dist-archive wp-content/plugins/hello-world`
  Then STDOUT should match /^Success: Created hello-world.0.1.0.zip \(Size: \d+(?:\.\d*)? [a-zA-Z]{1,3}\)$/

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^(STDOUT|STDERR) should( strictly)? (be|contain|not contain):$/

Check the contents of STDOUT or STDERR.


Usage

Scenario: My example scenario
  Given an empty directory
  When I run `wp core is-installed`
  Then STDOUT should be empty

Scenario: My other scenario
  Given a WP install
  When I run `wp plugin install akismet`
  Then STDOUT should contain:
    """
    Plugin installed successfully.
    """
  And STDERR should be empty

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^an email should (be sent|not be sent)$/

Expect an email to be sent (or not).


Usage

Scenario: My example scenario
  When I run `wp user reset-password 1`
  Then an email should be sent

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^STDOUT should be a JSON array containing:$/

Expect valid JSON array output in STDOUT.


Usage

Errors when some items are missing from the expected array.

Scenario: My example scenario
  When I run `wp plugin list --field=name --format=json`
  Then STDOUT should be a JSON array containing:
    """
    ["akismet", "hello-dolly"]
    """

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^STDOUT should be a table containing rows:$/

Expect STDOUT to be a table containing the given rows.


Usage

Scenario: My example scenario
  Given a WP installation
  When I run `wp config list --fields=name,type`
  Then STDOUT should be a table containing rows:
    | name    | type     |
    | DB_NAME | constant |
    | DB_USER | constant |

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^STDOUT should be CSV containing:$/

Expect STDOUT to be CSV containing certain values.


Usage

Scenario: My example scenario
  When I run `wp term list post_tag --fields=name,slug --format=csv`
  Then STDOUT should be CSV containing:
    | name      | slug |
    | Test term | test |

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^STDOUT should be JSON containing:$/

Expect valid JSON output in STDOUT.


Usage

Scenario: My example scenario
  When I run `wp post meta get 1 meta-key --format=json`
  Then STDOUT should be JSON containing:
    """
    {
    "foo": "baz"
    }
  """

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^STDOUT should be YAML containing:$/

Expect STDOUT to be YAML containing certain content.


Usage

Scenario: My example scenario
  When I run `wp cli alias list`
  Then STDOUT should be YAML containing:
    """
    @all: Run command against every registered alias.
    @foo:
      path: {TEST_DIR}/foo
    """

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^STDOUT should end with a table containing rows:$/

Expect STDOUT to end with a table containing the given rows.


Usage

Useful when the table is preceded by some other output.

Scenario: My example scenario
  Given a WP installation
  When I run `wp search-replace foo bar --report-changed-only`
  Then STDOUT should contain:
    """
    Success: Made 3 replacements.
    """
  And STDOUT should end with a table containing rows:
    | Table       | Column       | Replacements | Type |
    | wp_options  | option_value | 1            | PHP  |
    | wp_postmeta | meta_value   | 1            | SQL  |
    | wp_posts    | post_title   | 1            | SQL  |

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^the (.+) (file|directory) should( strictly)? (exist|not exist|be:|contain:|not contain:)$/

Expect a certain file or directory to (not) exist or (not) contain certain contents.


Usage

Scenario: My example scenario
  When I run `wp core download`
  Then the wp-settings.php file should exist
  And the wp-content directory should exist
  And the {RUN_DIR} directory should contain:
    """
    index.php
    license.txt
    """
  And the wp-config.php file should contain:
    """
    That's all, stop editing! Happy publishing.
    """

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^the contents of the (.+) file should( not)? match (((\/.+\/)|(#.+#))([a-z]+)?)$/

Match file contents against a regex.


Usage

Scenario: My example scenario
  When I run `wp scaffold plugin hello-world`
  Then the contents of the wp-content/plugins/hello-world/languages/hello-world.pot file should match /X-Generator:\s/

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then /^the return code should( not)? be (\d+)$/

Expect a specific exit code of the previous command.


Usage

Scenario: My example scenario
  Given a WP installation
  When I try `wp plugin install`
  Then the return code should be 1

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Then the HTTP status code should be :code

Expect the HTTP status code for visiting http://localhost:8080.


Usage

Scenario: My example scenario
  Given a WP installation with Composer
  And a PHP built-in web server to serve 'WordPress'
  Then the HTTP status code should be 200

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


Tools

The following is a list of projects that integrate with WP-CLI in some form. For installable WP-CLI packages, take a look at Packagist.

Plugins

The following table is an alphabetical list of known commands defined in WordPress plugins:

Command WordPress plugin
acf Advanced Custom Fields wp-cli
amt Add-Meta-Tags command line interface
any-ipsum Any Ipsum
backup BackUpWordPress
backwpup BackWPup
blog-dupe blog-duplicator
camptix CampTix
check-content CheckContent
co-authors-plus Co-Authors Plus
composer Composer
config WP-CFM
crontrol WP-Crontrol
csv Advanced CSV Importer
deploy wp-deploy-flow
developer Developer
edd Easy Digital Downloads
elasticpress ElasticPress
github-updater GitHub Updater
google-sitemap Google Sitemap Generator CLI
image-gen Image Gen
import_sidebar Widget Import Export
itelic Licensing for Exchange
jekyll-export WordPress to Jekyll Exporter
jetpack Jetpack by WordPress.com
liveblog Liveblog
mainwp MainWP
migrate WP Migrate DB CLI Interface
migratedb WP Migrate DB Pro
more-plugin-info More Plugin Info
multi-device Multi Device Switcher
nginx Nginx Cache Controller
optimize WP-Optimize
orderweight Order Weight for WooCommerce
p2-by-email P2 By Email
p2-resolved-posts P2 Resolved Posts
p2p Posts 2 Posts
pdf-light-viewer PDF Light Viewer
phpcompat PHP Compatibility Checker
post-gen Post Gen
quick-mail Quick Mail
rest-api-toolbox REST API Toolbox
redis-cache Redis Object Cache
revisions wp-revisions-cli
revision-strike Revision Strike
safe-redirect-manager Safe Redirect Manager
scheduled-unsticky Scheduled Unsticky
simple-history Simple History
site duplicate MultiSite Clone Duplicator
stream WP Stream
super-cache WP Super Cache CLI
supportpress SupportFlow
themecheck wp-cli-themecheck
thinkup Thinkup Import WP CLI Commands
total-cache W3 Total Cache
updraftplus UpdraftPlus
Unsplash Import images from Unsplash into your Media Library
wp2static Generate & deploy a static HTML version of your site
yoast Reindex Indexables on Yoast

If you implement a WP-CLI command in one of your plugins, please list it here.

Wrappers

Editor plugins

Vagrant boxes

Misc

When /^I (run|try) `([^`]+)` from '([^\s]+)'$/

Run or try a given command in a subdirectory.


Usage

run expects an exit code 0, whereas try allows for non-zero exit codes.

Scenario: My example scenario
  When I run `wp core is-installed`
  Then STDOUT should be empty

  When I run `wp core is-installed` from 'foo/wp-content'
  Then STDOUT should be empty

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


When /^I (run|try) `([^`]+)`$/

Run or try a given command.


Usage

run expects an exit code 0, whereas try allows for non-zero exit codes.

So if using run and the command errors, the step will fail.

Scenario: My example scenario
  When I run `wp core version`
  Then STDOUT should contain:
    """
    6.8
    """

Scenario: My other scenario
  When I try `wp i18n make-pot foo bar/baz.pot`
  Then STDERR should contain:
    """
    Error: Not a valid source directory.
    """
  And the return code should be 1

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


When /^I (run|try) the previous command again$/

Run or try the previous command again.


Usage

run expects an exit code 0, whereas try allows for non-zero exit codes.

Scenario: My example scenario
  When I run `wp site option update admin_user_id 1`
  Then STDOUT should contain:
    """
    Success: Updated 'admin_user_id' site option.
    """

  When I run the previous command again
  Then STDOUT should contain:
    """
    Success: Value passed for 'admin_user_id' site option is unchanged.
    """

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


When /^I launch in the background `([^`]+)`$/

Launch a given command in the background.


Usage

Scenario: My example scenario
  Given a WP install
  And I launch in the background `wp server --host=localhost --port=8181`
  ...

Behat steps documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::add_command()

Register a command to WP-CLI.


Usage

WP_CLI::add_command( $name, $callable, $args = [] )
$name (string) Name for the command (e.g. "post list" or "site empty").
$callable (callable|object|string|string[]) Command implementation as a class, function or closure.
$args (array) {
Optional. An associative array with additional registration parameters.
@type callable $before_invoke Callback to execute before invoking the command.
@type callable $after_invoke Callback to execute after invoking the command.
@type string $shortdesc Short description (80 char or less) for the command.
@type string $longdesc Description of arbitrary length for examples, etc.
@type string $synopsis The synopsis for the command (string or array).
@type string $when Execute callback on a named WP-CLI hook (e.g. before_wp_load).
@type bool $is_deferred Whether the command addition had already been deferred.
}
@return (bool) on success, false if deferred, hard error if registration failed.

Notes

WP-CLI supports using any callable class, function, or closure as a command. WP_CLI::add_command() is used for both internal and third-party command registration.

Command arguments are parsed from PHPDoc by default, but also can be supplied as an optional third argument during registration.

# Register a custom 'foo' command to output a supplied positional param.
#
# $ wp foo bar --append=qux
# Success: bar qux

/**
 * My awesome closure command
 *
 * <message>
 * : An awesome message to display
 *
 * --append=<message>
 * : An awesome message to append to the original message.
 *
 * @when before_wp_load
 */
$foo = function( $args, $assoc_args ) {
    WP_CLI::success( $args[0] . ' ' . $assoc_args['append'] );
};
WP_CLI::add_command( 'foo', $foo );

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::add_hook()

Schedule a callback to be executed at a certain point.


Usage

WP_CLI::add_hook( $when, $callback )
$when (string) Identifier for the hook.
$callback (callable) Callback to execute when hook is called.
@return (void)

Notes

Hooks conceptually are very similar to WordPress actions. WP-CLI hooks are typically called before WordPress is loaded.

WP-CLI hooks include:

The parentheses behind the hook name denote the number of arguments being passed into the hook. For such hooks, the callback should return the first argument again, making them work like a WP filter.

WP-CLI commands can create their own hooks with WP_CLI::do_hook().

If additional arguments are passed through the WP_CLI::do_hook() call, these will be passed on to the callback provided by WP_CLI::add_hook().

# `wp network meta` confirms command is executing in multisite context.
WP_CLI::add_command( 'network meta', 'Network_Meta_Command', array(
   'before_invoke' => function ( $name ) {
       if ( !is_multisite() ) {
           WP_CLI::error( 'This is not a multisite installation.' );
       }
   }
) );

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::add_wp_hook()

Add a callback to a WordPress action or filter.


Usage

WP_CLI::add_wp_hook( $tag, $function_to_add, $priority = 10, $accepted_args = 1 )
$tag (string) Named WordPress action or filter.
$function_to_add (callable) Callable to execute when the action or filter is evaluated.
$priority (integer) Priority to add the callback as.
$accepted_args (integer) Number of arguments to pass to callback.
@return (true)

Notes

add_action() without needing access to add_action(). If WordPress is already loaded though, you should use add_action() (and add_filter()) instead.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::colorize()

Colorize a string for output.


Usage

WP_CLI::colorize( $string )
$string (string) String to colorize for output, with color tokens.
@return (string) string.

Notes

Yes, you can change the color of command line text too. For instance, here's how WP_CLI::success() colorizes "Success: "

WP_CLI::colorize( "%GSuccess:%n " )

Uses \cli\Colors::colorize() to transform color tokens to display settings. Choose from the following tokens (and note 'reset'):

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::confirm()

Ask for confirmation before running a destructive operation.


Usage

WP_CLI::confirm( $question, $assoc_args = [] )
$question (string) Question to display before the prompt.
mixed> (array<string,) $assoc_args Skips prompt if 'yes' is provided.
@return (void)

Notes

If 'y' is provided to the question, the script execution continues. If 'n' or any other response is provided to the question, script exits.

# `wp db drop` asks for confirmation before dropping the database.

WP_CLI::confirm( "Are you sure you want to drop the database?", $assoc_args );

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::debug()

Display debug message prefixed with "Debug: " when --debug is used.


Usage

WP_CLI::debug( $message, $group = false )
$message (string|WP_Error|Exception|Throwable) Message to write to STDERR.
$group (string|bool) Organize debug message to a specific group.
Use `false` to not group the message.
@return (void)

Notes

Debug message is written to STDERR, and includes script execution time.

Helpful for optionally showing greater detail when needed. Used throughout WP-CLI bootstrap process for easier debugging and profiling.

# Called in `WP_CLI\Runner::set_wp_root()`.
private static function set_wp_root( $path ) {
    define( 'ABSPATH', Utils\trailingslashit( $path ) );
    WP_CLI::debug( 'ABSPATH defined: ' . ABSPATH );
    $_SERVER['DOCUMENT_ROOT'] = realpath( $path );
}

# Debug details only appear when `--debug` is used.
# $ wp --debug
# [...]
# Debug: ABSPATH defined: /srv/www/wordpress-develop.dev/src/ (0.225s)

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::do_hook()

Execute callbacks registered to a given hook.


Usage

WP_CLI::do_hook( $when, $args )
$when (string) Identifier for the hook.
...$args (mixed) Optional. Arguments that will be passed onto the
callback provided by `WP_CLI::add_hook()`.
@return (null|mixed) the first optional argument if optional<br /> arguments were passed, otherwise returns null.

Notes

See WP_CLI::add_hook() for details on WP-CLI's internal hook system. Commands can provide and call their own hooks.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::error()

Display error message prefixed with "Error: " and exit script.


Usage

WP_CLI::error( $message, $exit = true )
$message (string|WP_Error|Exception|Throwable) Message to write to STDERR.
$exit (boolean|int) True defaults to exit(1).
@return (null)

Notes

Error message is written to STDERR. Defaults to halting script execution with return code 1.

Use WP_CLI::warning() instead when script execution should be permitted to continue.

When --debug is enabled, this method will also output a backtrace showing where the error was triggered from, making it easier to identify problematic code.

# `wp cache flush` considers flush failure to be a fatal error.
if ( false === wp_cache_flush() ) {
    WP_CLI::error( 'The object cache could not be flushed.' );
}

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::error_multi_line()

Display a multi-line error message in a red box. Doesn't exit script.


Usage

WP_CLI::error_multi_line( $message_lines )
$message_lines (array<string|\WP_Error|\Exception|\Throwable>) Multi-line error message to be displayed.
@return (void)

Notes

Error message is written to STDERR.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::get_config()

Get values of global configuration parameters.


Usage

WP_CLI::get_config( $key = null )
$key (string) Get value for a specific global configuration parameter.
@return (mixed)

Notes

Provides access to --path=<path>, --url=<url>, and other values of the global configuration parameters.

WP_CLI::log( 'The --url=<url> value is: ' . WP_CLI::get_config( 'url' ) );

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::get_php_binary()

Get the path to the PHP binary used when executing WP-CLI.


Usage

WP_CLI::get_php_binary()
@return (string)

Notes

Environment values permit specific binaries to be indicated.

Note: moved to Utils, left for BC.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::halt()

Halt script execution with a specific return code.


Usage

WP_CLI::halt( $return_code )
$return_code (integer)
@return (never)

Notes

Permits script execution to be overloaded by WP_CLI::runcommand()

When --debug is enabled, this method will also output a backtrace showing where the halt was triggered from, making it easier to identify the cause of early termination.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::has_config()

Confirm that a global configuration parameter does exist.


Usage

WP_CLI::has_config( $key )
$key (string) Config parameter key to check.
@return (bool)

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::launch()

Launch an arbitrary external process that takes over I/O.


Usage

WP_CLI::launch( $command, $exit_on_error = true, $return_detailed = false )
$command (string) External process to launch.
$exit_on_error (boolean) Whether to exit if the command returns an elevated return code.
$return_detailed (boolean) Whether to return an exit status (default) or detailed execution results.
@return (int|ProcessRun) command exit status, or a ProcessRun object for full details.

Notes

# `wp core download` falls back to the `tar` binary when PharData isn't available
if ( ! class_exists( 'PharData' ) ) {
    $cmd = "tar xz --strip-components=1 --directory=%s -f $tarball";
    WP_CLI::launch( Utils\esc_cmd( $cmd, $dest ) );
    return;
}

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::launch_self()

Run a WP-CLI command in a new process reusing the current runtime arguments.


Usage

WP_CLI::launch_self( $command, $args = [], $assoc_args = [], $exit_on_error = true, $return_detailed = false, $runtime_args = [] )
$command (string) WP-CLI command to call.
string> (array<int,) $args Positional arguments to include when calling the command.
mixed> (array<string,) $assoc_args Associative arguments to include when calling the command.
$exit_on_error (bool) Whether to exit if the command returns an elevated return code.
$return_detailed (bool) Whether to return an exit status (default) or detailed execution results.
mixed> (array<string,) $runtime_args Override one or more global args (path,url,user,allow-root)
@return (int|ProcessRun) command exit status, or a ProcessRun instance

Notes

Use WP_CLI::runcommand() instead, which is easier to use and works better.

Note: While this command does persist a limited set of runtime arguments, it does not persist environment variables. Practically speaking, WP-CLI packages won't be loaded when using WP_CLI::launch_self() because the launched process doesn't have access to the current process $HOME.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::line()

Display informational message without prefix, and ignore --quiet.


Usage

WP_CLI::line( $message = '', $newline = true )
$message (string) Message to display to the end user.
$newline (bool) Optional. Whether to append a newline to the end of the message. Default true.
@return (void)

Notes

Message is written to STDOUT. WP_CLI::log() is typically recommended; WP_CLI::line() is included for historical compat.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::log()

Display informational message without prefix.


Usage

WP_CLI::log( $message, $newline = true )
$message (string) Message to write to STDOUT.
$newline (bool) Optional. Whether to append a newline to the end of the message. Default true.
@return (void)

Notes

Message is written to STDOUT, or discarded when --quiet flag is supplied.

# `wp cli update` lets user know of each step in the update process.
WP_CLI::log( sprintf( 'Downloading from %s...', $download_url ) );

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::read_value()

Read a value, from various formats.


Usage

WP_CLI::read_value( $raw_value, $assoc_args = [] )
$raw_value (string)
mixed> (array<string,) $assoc_args
@return (mixed)

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::run_command()

Run a given command within the current process using the same global parameters.


Usage

WP_CLI::run_command( $args, $assoc_args = [] )
string> (array<int,) $args Positional arguments including command name.
mixed> (array<string,) $assoc_args
@return (void)

Notes

Use WP_CLI::runcommand() instead, which is easier to use and works better.

To run a command using a new process with the same global parameters, use WP_CLI::launch_self(). To run a command using a new process with different global parameters, use WP_CLI::launch().

ob_start();
WP_CLI::run_command( array( 'cli', 'cmd-dump' ) );
$ret = ob_get_clean();

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::runcommand()

Run a WP-CLI command.


Usage

WP_CLI::runcommand( $command, $options = [] )
$command (string) WP-CLI command to run, including arguments.
mixed> (array<string,) $options {
Configuration options for command execution.
@type bool $launch Launches a new process (true) or reuses the existing process (false). Default: true.
@type bool $exit_error Halts the script on error. Default: true.
@type bool|string $return Returns output as an object when set to 'all' (string), return just the 'stdout', 'stderr', or 'return_code' (string) of command, or print directly to stdout/stderr (false). Default: false.
@type bool|string $parse Parse returned output as 'json' (string); otherwise, output is unchanged (false). Default: false.
@type array $command_args Contains additional command line arguments for the command. Each element represents a single argument. Default: empty array.
}
@return (mixed)

Notes

Launches a new child process to run a specified WP-CLI command. Optionally:

$options = array(
  'return'       => true,                // Return 'STDOUT'; use 'all' for full object.
  'parse'        => 'json',              // Parse captured STDOUT to JSON array.
  'launch'       => false,               // Reuse the current process.
  'exit_error'   => true,                // Halt script execution on error.
  'command_args' => [ '--skip-themes' ], // Additional arguments to be passed to the $command.
);
$plugins = WP_CLI::runcommand( 'plugin list --format=json', $options );

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::success()

Display success message prefixed with "Success: ".


Usage

WP_CLI::success( $message )
$message (string) Message to write to STDOUT.
@return (void)

Notes

Success message is written to STDOUT, or discarded when --quiet flag is supplied.

Typically recommended to inform user of successful script conclusion.

# wp rewrite flush expects 'rewrite_rules' option to be set after flush.
flush_rewrite_rules( \WP_CLI\Utils\get_flag_value( $assoc_args, 'hard' ) );
if ( ! get_option( 'rewrite_rules' ) ) {
    WP_CLI::warning( "Rewrite rules are empty." );
} else {
    WP_CLI::success( 'Rewrite rules flushed.' );
}

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI::warning()

Display warning message prefixed with "Warning: ".


Usage

WP_CLI::warning( $message )
$message (string|WP_Error|Exception|Throwable) Message to write to STDERR.
@return (void)

Notes

Warning message is written to STDERR, or discarded when --quiet flag is supplied.

Use instead of WP_CLI::debug() when script execution should be permitted to continue.

# `wp plugin activate` skips activation when plugin is network active.
$status = $this->get_status( $plugin->file );
// Network-active is the highest level of activation status
if ( 'active-network' === $status ) {
  WP_CLI::warning( "Plugin '{$plugin->name}' is already network active." );
  continue;
}

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\basename()

Locale-independent version of basename()


Usage

WP_CLI\Utils\basename( $path, $suffix = '' )
$path (string)
$suffix (string)
@return (string)

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\esc_like()

First half of escaping for LIKE special characters % and _ before preparing for MySQL.


Usage

WP_CLI\Utils\esc_like( $text )
$text (string) The raw text to be escaped. The input typed by the user should have no
extra or deleted slashes.
@return (string) in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()<br /> or real_escape next.

Notes

Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.

Copied from core "wp-includes/wp-db.php". Avoids dependency on WP 4.4 wpdb.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\format_items()

Render a collection of items as an ASCII table, JSON, CSV, YAML, list of ids, or count.


Usage

WP_CLI\Utils\format_items( $format, $items, $fields )
$format (string) Format to use: 'table', 'json', 'csv', 'yaml', 'ids', 'count'.
array<string, (array<int,) mixed>|object>|iterable|object> $items An array of items to output.
$fields (array<string>|string) Named fields for each item of data. Can be array or comma-separated list.
@return (void)

Notes

Given a collection of items with a consistent data structure:

$items = array(
    array(
        'key'   => 'foo',
        'value'  => 'bar',
    )
);

Render $items as an ASCII table:

WP_CLI\Utils\format_items( 'table', $items, array( 'key', 'value' ) );

# +-----+-------+
# | key | value |
# +-----+-------+
# | foo | bar   |
# +-----+-------+

Or render $items as YAML:

WP_CLI\Utils\format_items( 'yaml', $items, array( 'key', 'value' ) );

# ---
# -
#   key: foo
#   value: bar

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\get_flag_value()

Return the flag value or, if it's not set, the $default value.


Usage

WP_CLI\Utils\get_flag_value( $assoc_args, $flag, $default = null )
mixed> (array<string|int,) $assoc_args Arguments array.
$flag (string|int) Flag to get the value.
$default (mixed) Default value for the flag. Default: NULL.
@return (mixed)

Notes

Because flags can be negated (e.g. --no-quiet to negate --quiet), this function provides a safer alternative to using isset( $assoc_args['quiet'] ) or similar.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\get_home_dir()

Get the home directory.


Usage

WP_CLI\Utils\get_home_dir()
@return (string)

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\get_named_sem_ver()

Compare two version strings to get the named semantic version.


Usage

WP_CLI\Utils\get_named_sem_ver( $new_version, $original_version )
$new_version (string)
$original_version (string)
@return (string) 'minor', 'patch'

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\get_php_binary()

Get the path to the PHP binary used when executing WP-CLI.


Usage

WP_CLI\Utils\get_php_binary()
@return (string)

Notes

Environment values permit specific binaries to be indicated.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\get_temp_dir()

Get the system's temp directory. Warns user if it isn't writable.


Usage

WP_CLI\Utils\get_temp_dir()
@return (string)

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\http_request()

Make a HTTP request to a remote URL.


Usage

WP_CLI\Utils\http_request( $method, $url, $data = null, $headers = [], $options = [] )
$method (string) HTTP method (GET, POST, DELETE, etc.).
$url (string) URL to make the HTTP request to.
$data (array|null) Data to send either as a query string for GET/HEAD requests,
or in the body for POST requests.
$headers (array) Add specific headers to the request.
$options (array) {
Optional. An associative array of additional request options.
@type bool $halt_on_error Whether or not command execution should be halted on error. Default: true
@type bool|string $verify A boolean to use enable/disable SSL verification
or string absolute path to CA cert to use.
Defaults to detected CA cert bundled with the Requests library.
@type bool $insecure Whether to retry automatically without certificate validation.
@type int $max_retries Maximum number of retries of failed requests. Default 3.
}
$method (string) HTTP method.
$url (string) URL to request.
mixed>|string|null (array<string,) $data Array of data to send or string.
string> (array<string,) $headers Array of headers to send.
mixed> (array<string,) $options Array of options for the request.
@return (\Requests_Response|Response)

Notes

Wraps the Requests HTTP library to ensure every request includes a cert.

# `wp core download` verifies the hash for a downloaded WordPress archive

$md5_response = Utils\http_request( 'GET', $download_url . '.md5' );
if ( 20 != substr( $md5_response->status_code, 0, 2 ) ) {
     WP_CLI::error( "Couldn't access md5 hash for release (HTTP code {$response->status_code})" );
}

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\is_stream()

Check if a path is a PHP stream URL.


Usage

WP_CLI\Utils\is_stream( $path )
$path (string) The resource path or URL.
@return (bool) if the path is a PHP stream URL, false otherwise.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\isPiped()

Checks whether the output of the current script is a TTY or a pipe / redirect


Usage

WP_CLI\Utils\isPiped()
@return (bool)

Notes

Returns true if STDOUT output is being redirected to a pipe or a file; false is output is being sent directly to the terminal.

If an env variable SHELL_PIPE exists, the returned result depends on its value. Strings like 1, 0, yes, no, that validate to booleans are accepted.

To enable ASCII formatting even when the shell is piped, use the ENV variable SHELL_PIPE=0.

SHELL_PIPE=0 wp plugin list | cat

Note that the db command forwards to the mysql client, which is unaware of the env variable. For db commands, pass the --table option instead.

wp db query --table "SELECT 1" | cat

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\launch_editor_for_input()

Launch system's $EDITOR for the user to edit some text.


Usage

WP_CLI\Utils\launch_editor_for_input( $input, $title = WP-CLI, $ext = tmp )
$input (string) Some form of text to edit (e.g. post content).
$title (string) Title to display in the editor.
$ext (string) Extension to use with the temp file.
@return (string|bool) text, if file is saved from editor; false, if no change to file.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\make_progress_bar()

Create a progress bar to display percent completion of a given operation.


Usage

WP_CLI\Utils\make_progress_bar( $message, $count, $interval = 100 )
$message (string) Text to display before the progress bar.
$count (integer) Total number of ticks to be performed.
$interval (int) Optional. The interval in milliseconds between updates. Default 100.
@return (\cli\progress\Bar|\WP_CLI\NoOp)

Notes

Progress bar is written to STDOUT, and disabled when command is piped. Progress advances with $progress->tick(), and completes with $progress->finish(). Process bar also indicates elapsed time and expected total time.

# `wp user generate` ticks progress bar each time a new user is created.
#
# $ wp user generate --count=500
# Generating users  22 % [=======>                             ] 0:05 / 0:23

$progress = \WP_CLI\Utils\make_progress_bar( 'Generating users', $count );
for ( $i = 0; $i < $count; $i++ ) {
    // uses wp_insert_user() to insert the user
    $progress->tick();
}
$progress->finish();

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\make_temp_dir()

Create a unique temporary directory safely without following symlinks.


Usage

WP_CLI\Utils\make_temp_dir( $prefix = wp-cli- )
$prefix (string) Optional. Prefix for the temporary directory name. Default 'wp-cli-'.
@return (string) to the created temporary directory with a trailing slash.

Notes

The directory is only accessible by its owner on non-Windows systems.

The directory is created in the directory returned by WP-CLI's get_temp_dir() (based on sys_get_temp_dir()), not WordPress's get_temp_dir(), and is not removed automatically; callers are responsible for cleaning it up.

On failure, this function exits via WP_CLI::error() rather than throwing.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\make_temp_file()

Create a unique temporary file safely without following symlinks.


Usage

WP_CLI\Utils\make_temp_file( $prefix = wp-cli-, $suffix = '' )
$prefix (string) Optional. Prefix for the temporary file name. Default 'wp-cli-'.
$suffix (string) Optional. Suffix for the temporary file name. Default ''.
@return (string) to the created temporary file.

Notes

The file is only readable and writable by its owner on non-Windows systems.

The file is created in the directory returned by WP-CLI's get_temp_dir() (based on sys_get_temp_dir()), not WordPress's get_temp_dir(), and is not removed automatically; callers are responsible for cleaning it up.

On failure, this function exits via WP_CLI::error() rather than throwing.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\normalize_path()

Normalize a filesystem path.


Usage

WP_CLI\Utils\normalize_path( $path )
$path (string) Path to normalize.
@return (string) path.

Notes

On Windows systems, replaces backslashes with forward slashes and forces upper-case drive letters. Allows for two leading slashes for Windows network shares, but ensures that all other duplicate slashes are reduced to a single one. Ensures upper-case drive letters on Windows systems. Allows for PHP file wrappers.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\parse_ssh_url()

Parse a SSH url for its host, port, and path.


Usage

WP_CLI\Utils\parse_ssh_url( $url, $component = -1 )
$url (string)
$component (int)
@return (mixed)

Notes

Similar to parse_url(), but adds support for defined SSH aliases.

host OR host/path/to/wordpress OR host:port/path/to/wordpress

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\parse_str_to_argv()

Parse a string of command line arguments into an $argv-esqe variable.


Usage

WP_CLI\Utils\parse_str_to_argv( $arguments )
$arguments (string)
@return (array<string>)

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\proc_open_compat()

Windows compatible proc_open(). Works around bug in PHP, and also deals with *nix-like ENV_VAR=blah cmd environment variable prefixes.


Usage

WP_CLI\Utils\proc_open_compat( $cmd, $descriptorspec, $pipes, $cwd = null, $env = null, $other_options = null )
$cmd (string) Command to execute.
list<string>|resource> (array<int,) $descriptorspec Indexed array of descriptor numbers and their values.
resource> (array<int,) &$pipes Indexed array of file pointers that correspond to PHP's end of any pipes that are created.
$cwd (string) Initial working directory for the command.
string> (array<string,) $env Array of environment variables.
bool>|null (array<string,) $other_options Array of additional options (Windows only).
array<int, (@param-out) resource> $pipes
@return (resource|false) stripped of any environment variable settings, or false on failure.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\report_batch_operation_results()

Report the results of the same operation against multiple resources.


Usage

WP_CLI\Utils\report_batch_operation_results( $noun, $verb, $total, $successes, $failures, $skips = null )
$noun (string) Resource being affected (e.g. plugin).
$verb (string) Type of action happening to the noun (e.g. activate).
$total (integer) Total number of resource being affected.
$successes (integer) Number of successful operations.
$failures (integer) Number of failures.
$skips (null|integer) Optional. Number of skipped operations. Default null (don't show skips).
@return (void)

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\trailingslashit()

Appends a trailing slash.


Usage

WP_CLI\Utils\trailingslashit( $string )
$string (string) What to add the trailing slash to.
@return (string) with trailing slash added.

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.


WP_CLI\Utils\write_csv()

Write data as CSV to a given file.


Usage

WP_CLI\Utils\write_csv( $fd, $rows, $headers = [] )
$fd (resource) File descriptor.
mixed>> (array<string[]>|iterable<array<string,) $rows Array of rows to output.
$headers (array<string>) List of CSV columns (optional).
@return (void)

Internal API documentation is generated from the WP-CLI codebase on every release. To suggest improvements, please submit a pull request.