WP-CLI Packages: Supercharge Your WordPress Development

#
By Mike Davey, Senior Editor

WP-CLI packages take the increased efficiency of the command line even further by extending it with new or modified commands. In this article, we’ll show you how to install packages, highlight some favorites, and give you ways to search for other packages to improve your development workflow.

What are WP-CLI Packages?

Packages for WP-CLI are kind of like plugins for WordPress. Just like packages, plugins can provide their own commands to a site, but packages have the advantage of being available globally. You can install a package once and use it on multiple sites running on the same server. Packages can also run before WordPress is loaded, or even in directories where WordPress is not yet installed, like Matt’s great wp-installer package.

How to Install WP-CLI Packages

The first step is to install WP-CLI if you haven’t already. Once wp-cli.phar is in place and added to your path, you’re ready to start installing packages.

All WP-CLI commands share a similar structure: a parent command followed by a subcommand, supplemented with options and other arguments. Parent commands and subcommands are usually descriptive. For example, the command for plugin installs is wp plugin install. Adding activate as a parameter will activate it at the same time. Manage your plugins with WP-CLI is often more efficient than doing it through the admin, plus you can pull off neat tricks like comparing your plugin checksums and include Bash scripts that perform different actions based on whether or not a particular plugin is installed.

When dealing with WP-CLI packages, the parent command is wp package and the following command is usually install. You can install any package by using wp package install followed by the package specified as a Git URL, a local path to a directory, or with a local or remote zip file. In the case of local directories, WP-CLI just registers the directory’s location. The reference will break if you move or delete that directory.

# Install a Git URL package
wp package install matt/wp-installer

# Install the package from a local directory
wp package install /path/to/mypackage

# Install the package from a zip file
wp package install sample-package.zip

Regardless of the source, all WP-CLI packages are installed in ~/.wp-cli/packages/. Use the WP_CLI_PACKAGES_DIR environment variable if you want to use a custom path instead.

In addition to install, one of the more useful subcommands is list, which shows you the packages you currently have:

+----------------------------------+---------------------------------+------------+-----------+----------------+
| name                             | authors                         | version    | update    | update_version |
+----------------------------------+---------------------------------+------------+-----------+----------------+
| alleyinteractive/wp-doc-command  |                                 | dev-main   | none      |                |
| binarygary/db-checkpoint         | Gary Kovar                      | dev-master | none      |                |
| iandunn/wp-cli-rename-db-prefix   | Ian Dunn                        | dev-master | none      |                |
| matt/wp-installer                | Matt Shaw                       | dev-master | none      |                |
| wp-cli/doctor-command            | Daniel Bachhuber                | dev-main   | none      |                |
| wp-cli/package-command           | Daniel Bachhuber                | dev-main   | available | 2.x-dev        |
| wp-cli/php-cli-tools             | Daniel Bachhuber, James Logsdon | dev-master | none      |                |
| wp-cli/profile-command            |                                 | dev-master | available | 2.x-dev        |
| yoast/wp-cli-faker               | Herre Groen                     | dev-master | none      |                |
+----------------------------------+---------------------------------+------------+-----------+----------------+

Best Packages for WordPress Developers

There are hundreds of WP-CLI packages available right now, with more being created all the time. Below are just a few that we’ve found to be super useful. All of the packages listed below can be installed with wp package install followed by the Git URL provided in the heading.

schlessera/wp-cli-psysh (#psysh-command)

Perhaps you are already familiar with the wp shellcommand that allows you to execute PHP commands in the context of WordPress in a REPL (Read-Eval-Print-Loop) environment. Once you have started wp shell, you can type any PHP expression and see the return values printed.

This is an excellent way to quickly test small pieces of PHP without having to edit code files. However, the built-in wp shell REPL is a bit clunky and quite unforgiving. It’s common that a small typo throws you out completely, which means you need to start from the beginning again.

wp shell
wp> $id = 61;
=> int(61)
wp> wp> wp_get_attachment_image_src( $id ): // ←- Accidental colon instead of semicolon:
Error: There has been a critical error on this website. Learn more about troubleshooting WordPress. There has been a critical error on this website. 

This is where schlessera/wp-cli-psysh comes in handy. It simply replaces the REPL component from the standard wp shell with PsySH, which has a lot more polish to it.

wp shell
Psy Shell v0.11.8 (PHP 7.4.30 — cli) by Justin Hileman
>>> $id = 61;
=> 61

>>> wp_get_attachment_image_src( $id ): // ←- Accidental colon instead of semicolon:
PHP Parse error: Syntax error, unexpected ':' on line 1
>>> wp_get_attachment_image_src( $id );
=> [
     "http://www.hellfish.media/wp-content/uploads/2022/08/11142407/image2.png",
     150,
     84,
     false,
   ]

>>>

First and foremost, it’s fault tolerant, saving you tons of frustration when your fingers slip in that accidental typo. The output formatting is also a lot more polished, which makes it easier to read. Italso has built-in tab completion for all WordPress functions, making it easier to find the exact name of the function you’re after.

aaemnnosttv/wp-cli-login-command (#login-command)

This package is mostly useful for production servers. The wp-cli-login-command creates magic login links for any existing WordPress user on a site. This is handy for impersonating other users during troubleshooting, or to provide a way to let users login to reset their password. The links expire after 15 minutes or after being used once, whichever comes first.

To get started with wp-cli-login-command you need to do two things: install the package for WP-CLI, and install the companion plugin on the target WordPress site:

wp package install aaemnnosttv/wp-cli-login-command
…
….
Success: Package installed.
wp login install
Success: Companion plugin installed.
wp plugin list –field=name
hello
wp-cli-login-server

Once the plugin is installed it’s easy to use:

# Create a link the standard way:
wp login create admin
Success: Magic login link created!
-----------------------------------------------------------
https://www.hellfish.media/daaf8887/0bc301-829e5b8e-11b46634
-----------------------------------------------------------
This link will self-destruct in 15 mins, or as soon as it is used; whichever comes first.

# Just return the link, suitable for bash scripting:
wp login  create admin --url-only
https://www.hellfish.media/daaf8887/537604-de26e1-c6c67807f9

The wp-cli-login-command package is flexible, allowing you to control the link expiry time and decide which URL to redirect to after successful login.

Another cool feature is that you can ask WordPress to send the login link to the registered email address of the user. This is essentially a very quick way to provide password reset links for your users:

wp login email admin --expires=240
Success: Email sent.

alleyinteractive/wp-doc-command

The wp-doc-command is an incredibly useful tool for developers when you need a little more information about a WordPress core function than your IDE is willing to show.

Rather than go searching through the code reference, you can just pop open your CLI and run wp doc [...] to get the PHPDoc output of pretty much anything in WordPress that’s documented (which is everything).

    > wp doc __return_true
    Documentation for function '__return_true()' in wp-includes/functions.php:4835
    ==============================================================================
    
      Returns true.
      Useful for returning true to filters easily.
    
    SINCE
      3.0.0
    SEE
      __return_false()
    
    RETURN   true
      True.

Super useful, especially for all of the WordPress functions that don’t start with __return_.

binarygary/db-checkpoint

As the About section at db-checkpoint puts it, this package “adds a new command to WP-CLI so you can treat your DB like a save point in a video game.” In other words, it lets you try stuff out and quickly roll back all the changes.

Once you’ve installed the package, you can take a snapshot of the database in your WordPress installation by running wp dbsnap. You can then try out whatever you like, and if it ends up breaking your site, you can restore it very quickly. You don’t even need to remember what you named your backup file. Just run wp dbsnapback and your database is returned to the state when you took the snapshot. Nobody will ever know about all of that stuff you messed up!

In all seriousness, this is a very useful package when you want to test changes to your database and you’re not sure what the results will be. It’s also handy for those situations where you are sure you know what the results will be…but you turn out to be wrong.

wp dbsnap
Success: Exported to '/var/www/productionsite.com/wp-content/uploads/checkpoint-storage/secure.20180119-0506.sql'.
Success: Checkpoint Saved!
    
# I'm going to change my site url to get all of the traffic!
> wp option set siteurl http://google.com
Success: Updated 'siteurl' option.
    
# Just checking to make sure that worked...
wp option get siteurl
http://google.com

# D’oh! Put it back, put it back!
wp dbsnapback
This is a destructive operation, are you sure? [y/n] y
Are you sure you want to reset the 'production-db' database? [y/n] y
Success: Database reset.
Success: Imported from '/var/www/productionsite.com/wp-content/uploads/checkpoint-storage/secure.20180119-0506.sql'.
Success: Checkpoint Restored!

iandunn/wp-cli-rename-db-prefix

The wp-cli-rename-db-prefix package is handy when you need to change your table prefix, for example when you’re migrating data to a site that uses a prefix different from the one on your dev site. WP Migrate Pro updates table prefixes automatically, but other tools may not.

With that said, be careful with how you use this package. A wrong move here could break your site. Make sure to back up wp-config.php and export your database before you start monkeying around with the prefix.

The basic command is wp rename-db-prefix <new_prefix>, but there are a couple of options you can hang on that:

  • --dry-run: This shows the results of running the command without making any permanent changes. This is very handy if you’re a cautious person.
  • --no-confirm: The package normally prompts you before making changes. This option prevents that from happening, if you’re the opposite of a cautious person.
  • --no-config-update: This runs the command without updating your wp-config.php.

The package doesn’t bother with the prompt when you use --dry-run, but it does let you see exactly what’s going to be changed:

wp rename-db-prefix flyinghellfish_ --dry-run
Running in dry run mode.

RENAME TABLE `wp_commentmeta` TO `flyinghellfish_commentmeta`;
RENAME TABLE `wp_comments` TO `flyinghellfish_comments`;
RENAME TABLE `wp_links` TO `flyinghellfish_links`;
RENAME TABLE `wp_options` TO `flyinghellfish_options`;
RENAME TABLE `wp_postmeta` TO `flyinghellfish_postmeta`;
RENAME TABLE `wp_posts` TO `flyinghellfish_posts`;
RENAME TABLE `wp_term_relationships` TO `flyinghellfish_term_relationships`;
RENAME TABLE `wp_term_taxonomy` TO `flyinghellfish_term_taxonomy`;
RENAME TABLE `wp_termmeta` TO `flyinghellfish_termmeta`;
RENAME TABLE `wp_terms` TO `flyinghellfish_terms`;
RENAME TABLE `wp_usermeta` TO `flyinghellfish_usermeta`;
RENAME TABLE `wp_users` TO `flyinghellfish_users`;

                        UPDATE `flyinghellfish_options`
                        SET   option_name = 'flyinghellfish_user_roles'
                        WHERE option_name = 'wp_user_roles'
                        LIMIT 1;

                                UPDATE `flyinghellfish_usermeta`
                                SET meta_key='flyinghellfish_capabilities'
                                WHERE meta_key='wp_capabilities'
                                LIMIT 1;

                                UPDATE `flyinghellfish_usermeta`
                                SET meta_key='flyinghellfish_user_level'
                                WHERE meta_key='wp_user_level'
                                LIMIT 1;
Success: Successfully renamed database prefix.

For standard installs, the rename-db-prefix command turns this otherwise annoying task into something that barely requires a second thought. We’re with the package contributors on this one, though: use at your own risk. It’s a convenient tool if you know what you’re doing, and a short trip to a lot of pain if you don’t.

Yoast/wp-cli-faker

WP CLI Faker can generate fake data for both WordPress core and WooCommerce, making it useful for testing purposes. I didn’t have any trouble installing it with the standard method, but the installation instructions note that the default memory limits are often not enough to run Composer, and recommends the following instead:

php -d memory_limit=512M "$(which wp)" package install [email protected]:Yoast/wp-cli-faker.git

It’s also possible to install WP CLI Faker as a plugin by cloning the repo into your WordPress plugins folder, but you’ll have to install dependencies with Composer 1.x by running php composer.phar install.

WP CLI Faker has two commands: wp faker core content and wp faker woocommerce products. Both commands have flags you can add to change the exact type and amount of fake content being generated. If you don’t use a particular flag, the package generates that type of fake content at a default value.

wp faker core content --authors=12 --categories=9 --posts=150

author generation  100% [==========================================] 0:01 / 0:02
category generation  100% [==========================================] 0:00 / 0:00
tag generation  100% [==========================================] 0:00 / 0:00
attachment generation  100% [==========================================] 0:09 / 0:12
post generation  100% [==========================================] 0:12 / 0:19
page generation  100% [==========================================] 0:00 / 0:00

wp-cli/doctor-command

The idea behind wp-cli/doctor-command is to enable teams to codify diagnosis procedures for WordPress installs, saving time when it comes to identifying site health issues.

After installing the package, tests can be run with the wp doctor command and the check subcommand, followed by flags indicating which tests you want to run. Using the --all flag will run every test available. Combining it with the --spotlight flag will show only what’s ailing on your site, while ignoring all of the successful checks:

wp doctor check --all --spotlight
Running checks  100% [=======================================================] 0:12 / 0:07
+-----------------------+---------+-------------------------------------------------+
| name                  | status  | message                                         |
+-----------------------+---------+-------------------------------------------------+
| cache-flush            | warning | Use of wp_cache_flush() detected.                |
| php-in-upload         | warning | PHP files detected in the Uploads folder.        |
+-----------------------+---------+-------------------------------------------------+

The package also includes options for piping the results into other systems with --format=json and --format=csv, as well as the ability to write custom configuration files in YAML to define additional checks.

Finding New WP-CLI Packages

The WP-CLI package index is a goldmine of incredibly useful commands, but it’s also pretty much dead. The index has been deprecated, although it’s still in place to ensure backwards compatibility and wp package browse will still show you the packages available in the index.

Fortunately, you can also find new WP-CLI packages at Packagist. Some of the packages you’ll see listed are already part of WP-CLI, but there are plenty that extend its functionality into new areas, such as wp-cli/profile-command, that monitors KPIs of the WordPress execution process.

If you don’t find what you’re looking for at Packagist, you can always write your own commands and create your own packages.

Creating WP-CLI Packages

The first step in creating a new WP-CLI package is writing custom commands. This process is thoroughly documented in the Commands Cookbook, but we’ve included a brief version here..

You can register your custom WP-CLI commands with WP_CLI::add_command(). This requires two arguments, name, which is the new command’s namespace in WP-CLI, and callable, which is the part that implements the command, such as a callable class, function, or closure.

New commands can be registered to their own namespace or added as subcommands to an existing namespace. To do this, you need to include the existing namespace in the command definition you’re registering.

class Hellfish_Command {
    public function __invoke( $args ) {
        WP_CLI::success( $args[0] );
    }
}
WP_CLI::add_command( 'core hellfish', 'Hellfish_Command' );

As it stands, this command won’t support any arguments. We need to add two more arguments to our command registration: args, which contain positional arguments, and assoc_args, which contain arguments declared with flags.

Once you’ve created a command, you can bundle it into a WordPress plugin or theme, or release it as a standalone package with wp scaffold package, after installing it via its repository.

Wrapping Up

WP-CLI packages extend the functionality of WP-CLI with new commands and new capabilities to aid in your development workflow. Packages are similar to plugins in some ways, but even more useful, as you can install them globally and they’ll never slow down your sites.

The packages presented here are a good starting point, but some time spent browsing Packagist will help you find other invaluable tools.

What are your favorite packages? Do you use any you’ve built yourself? Let us know in the comments!

About the Author

Mike Davey Senior Editor

Mike is an editor and writer based in Hamilton, Ontario, with an extensive background in business-to-business communications and marketing. His hobbies include reading, writing, and wrangling his four children.