https://deliciousbrains.com/complete-guide-to-installing-wp-cli/
complete guide to installing wp-cli
https://deliciousbrains.com/complete-guide-to-installing-wp-cli/
The WordPress command line interface (WP-CLI) is a powerful WordPress-developer focused tool. Here at Delicious Brains we use it to help us write tests, manage changes to our site databases, and we even have WP-CLI support in WP Migrate DB Pro. Last but not least, SpinupWP, our cloud based server control panel for WordPress, makes heavy use of WP-CLI to manage WordPress sites, so it is an incredibly important tool for us.
We love it so much, we think it’s important that every WordPress developer knows how to install and use it. This post will cover installing WP-CLI and setting it up to work efficiently with this amazing tool.
#Table of Contents
How to Install WP-CLI on macOS and Linux
How to Install WP-CLI on Windows
After Installing WP-CLI
#What Is WP-CLI?
WP-CLI is a command line interface for WordPress. It allows you to do many of the same tasks as the administration panel on your WordPress site, but from a command line terminal on your computer or a web server. This makes it very useful both during development and once the site is deployed. You can use WP-CLI to install WordPress, configure multisite installations, update plugins and themes, update WordPress itself, and much more.
Once you feel comfortable with WP-CLI, you will find this is often quicker than doing the same thing via the web browser (and it makes you look really cool while doing it).
Command line tools like WP-CLI are also great for repetitive tasks, like adding users in bulk or checking for updates on a regular basis. This is because WP-CLI is easy to combine with other command line tools and utilities like Bash scripts and cron jobs.
People use WP-CLI for a wide variety of WordPress related tasks. For example…
Installing and activating a plugin:
$ wp plugin --activate advanced-custom-fields
Adding a user:
$ wp user create erik erik@hellfish.media --role=subscriber
Updating WordPress core and the database:
$ wp core update && wp core update-db
Taking a snapshot of the database:
$ wp db export /mnt/backups/$(date +%Y%m%d).sql
Adding a single user, running one-off backups, or performing update checks using the command line might not be a big win over using the administration pages. However, if you have 500 users to add, or want to get updates and backups done at 3 a.m. every morning, having a command line tool becomes really handy.
We’ll go in-depth on how to get the most out of WP-CLI in a future tutorial, including hints, tips, and tricks that the Delicious Brains team have picked up over the years. But first things first, let’s get WP-CLI properly installed.
#How to Install WP-CLI
These instructions are for Mac and Linux users. Click here to jump to the instructions for installing on Windows.
#The Official Method
The recommended way to install WP-CLI is documented on the WP-CLI site. Installing WP-CLI on a Mac or Linux machine requires PHP version 5.6 or later and you must have the cURL command line tool installed. Open your terminal and run the following commands.
The first step is to download the Phar build:
$ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
Next, you need to verify the downloaded file:
$ php wp-cli.phar --info
Finally, make it executable and move it into your PATH:
$ chmod +x wp-cli.phar
$ sudo mv wp-cli.phar /usr/local/bin/wp
#Installing WP-CLI Using a Package Manager
The WP-CLI developers are not actively involved in maintaining packages for the multitude of package managers. The options for installing WP-CLI using a package manager vary depending on which package manager you use and if any volunteers have stepped in and created a package for it.
#Installing WP-CLI Using APT
Tiago Hillebrandt maintains a PPA for installing WP-CLI on Debian/Ubuntu and all its variations. You can use his PPA like this:
$ sudo add-apt-repository ppa:tiagohillebrandt/wp-cli
$ sudo apt-get update
$ sudo apt-get install wp-cli
#Installing WP-CLI Using Homebrew
Homebrew has a formula for WP-CLI, so it’s a matter of running the following command:
$ brew install wp-cli
#Installing WP-CLI Using Composer
You can also use Composer to install WP-CLI. While the most common use for Composer is to maintain dependencies inside your PHP project, it can also be used to install tools on your machine. It’s possible to install WP-CLI just for your current project if you absolutely need to have a specific WP-CLI version. It is quite rare that a project needs anything other than the latest version, so my recommendation is to install it globally. It’s nice to have WP-CLI easily accessible everywhere and it’s one less dev dependency in my projects. Here’s how to install it globally:
$ composer global require wp-cli/wp-cli
This installation method requires you to add ~/.composer/vendor/bin
to your PATH variable. This works differently depending on whether you’re using MacOS, Linux, or Windows. Here are some useful links for using Bash or Zsh.
Once you have installed WP-CLI globally like this, you can reach it from any folder on your computer.
#Installing WP-CLI via Docker
The Docker community maintains WordPress and WP-CLI images. You can use the WP-CLI image in your Docker projects by specifying the CLI variant as your WordPress image in the yml
file created by docker compose
.
image: wordpress:cli
#Verifying That WP-CLI Works
Regardless of which installation method you use, it’s a good idea to verify that the installation succeeded and WP-CLI is accessible regardless of which directory you happen to be in. To verify that things work as they should, you can pass the --info
parameter:
$ wp --info
If it’s installed correctly, you should see something like this:
OS: Darwin 20.6.0 Darwin Kernel Version 20.6.0: Wed Nov 10 22:23:07 PST 2021; root:xnu-7195.141.14~1/RELEASE_X86_64 x86_64
Shell: /bin/zsh
PHP binary: /usr/local/Cellar/php@7.4/7.4.27/bin/php
PHP version: 7.4.27
php.ini used: /usr/local/etc/php/7.4/php.ini
MySQL binary: /usr/local/bin/mysql
MySQL version: mysql Ver 8.0.28 for macos11.6 on x86_64 (Homebrew)
SQL modes:
WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir: phar://wp-cli.phar/vendor
WP_CLI phar path: /usr/local/bin
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.6.0
#How to Install WP-CLI on Windows
Installing WP-CLI on native Windows is slightly different from installing it on a Mac or Linux machine. Before we start, using the Windows Subsystem for Linux that Microsoft introduced a few years ago you should be able to install using the instructions for MacOS and Linux above. If you want it working under native Windows the following steps are for you.
Please be aware that WP-CLI is first and foremost made for *nix based systems. Some functionality, like accessing remote WordPress sites via SSH, may require you to jump through quite a few hoops. Other features may not work at all. But getting a basic installation of WP-CLI up and running on a Windows machine is possible.
Note that your Windows user account must have administrator rights for these steps to work. If you don’t have administrator rights, then you need to ask someone that does to either give you administrator rights or help you out with these steps.
#Windows Requirements
To get started with installing the WordPress command line on Windows, the only real requirements are that you have command line PHP for Windows installed and added to your PATH so that you can run PHP from the command line in any working directory. The easiest way to install WP-CLI is by using cURL. Most Windows installations already have cURL installed, as it’s been included with Windows 10 since 2018.
If you don’t already have it on your machine I highly recommend you install it using one of these suggested methods or by downloading it from the cURL home page before continuing.
#Download and Install
First you need to download the latest build of the wp-cli.phar from GitHub into a local folder. If you have cURL installed you can do this with three commands:
C:\> mkdir C:\wp-cli
C:\> cd C:\wp-cli
C:\> curl -O https://raw.github.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
If you don’t have cURL and can’t install it, you can also create the C:\wp-cli
folder in your Windows File Explorer manually, download the file using the link above, and then move it to that folder.
After downloading the file, it’s a good idea to confirm it works by typing:
C:> php C:\wp-cli\wp-cli.phar --info
You should see a couple of lines summarizing your local WP-CLI environment.
Typing the full path to the phar file every time you run a WP-CLI command is going to get old really fast. So to make life a little easier, we are going to do two more steps. First we permanently add the C:\wp-cli
folder to the PATH environment variable. I prefer to do this using the setx
command. You can select between adding it to just your environment or adding it for all users by using the /m
switch.
For all future sessions with your user account:
setx PATH "%PATH%;c:\wp-cli"
For just the current terminal session:
set PATH "%PATH%;c:\wp-cli"
Or for all future sessions, for all users on the system:
setx PATH "%PATH%;c:\wp-cli" /m
Just adding the path to your own environment is fine if this is your local development machine. If it is a server where you will potentially schedule nightly jobs using WP-CLI, it’s better to add it to the environment for all users. Using setx
with the /m
switch requires you to open a CMD terminal with full administrative rights. The easiest way to do that is to search for cmd.exe
on the Start menu, right click it, and select Run as administrator to open it:
Finally, we create a windows batch file in the WP-CLI folder named wp.bat
with the following content:
@ECHO OFF
php "c:\wp-cli\wp-cli.phar" %*
This .bat
file will enable you to call run WP-CLI using the shorter wp
instead of always typing the full name of the phar file. It saves you a bunch of typing and it is also how WP-CLI is called on Mac and Linux.
#Verifying That WP-CLI Works on Windows
With all of the above in place, we should now be able to run WP-CLI from any folder:
C:\> wp --info
If it’s installed correctly, you should see something like this:
OS: Windows NT 10.0 build 19043 (Windows 10) AMD64
Shell: C:\WINDOWS\system32\cmd.exe
PHP binary: C:\php\php.exe
PHP version: 7.4.27
php.ini used:
MySQL binary:
MySQL version:
SQL modes:
WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir: phar://wp-cli.phar/vendor
WP_CLI phar path: C:\wp-cli
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.6.0
#After Installing WP-CLI
Once you have WP-CLI up and running and have verified that it works, it’s time for some initial setup. One of the core concepts of WP-CLI is commands
that can have subcommands
. Each of these commands and subcommands can have a bunch of optional switches. You can sometimes end up typing pretty long command strings. Just the other day I needed to insert an array element inside a WordPress option and the command ended up like this:
$ wp --path=www/testing option patch insert tantan_wordpress_s3 post_meta_version 7
Once you get comfortable with WP-CLI, you will no doubt learn a lot of these commands by heart. But if this looks like more typing than you like to do on a regular basis, let me show you some things you can do to make it feel less daunting and a lot more likely to be correct on the first attempt.
#Setting Up Tab Completion
The first thing we’re going to do is enable tab completion, which is the mechanism in the shell that automatically suggests what you should type next when you hit the TAB
key. In my environment, I just type the start of that command above to see which subcommands there are:
$ wp option [TAB]
add delete get list patch pluck update
Setting up tab completion is too easy to not do it, but it helps to know which command line shell you are using. If you’re not sure, let me quickly show you how to do that by checking the $SHELL environment variable:
# On older MacOS and on most Linux boxes, we should see /bin/bash
$ echo $SHELL
/bin/bash
# On newer MacOS boxes, we should see /bin/zsh
$ echo $SHELL
/bin/zsh
# Check for Oh My Zsh
$ omz
Usage: omz <command> [options]
Available commands:
help Print this help message
changelog Print the changelog
plugin <command> Manage plugins
pr <command> Manage Oh My Zsh Pull Requests
reload Reload the current zsh session
theme <command> Manage themes
update Update Oh My Zsh
version Show the version
If you are using Oh My Zsh this is the easiest thing ever. Just type the following command:
$ omz plugin enable wp-cli
omz::plugin::enable: plugins enabled: wp-cli.
If you are using straight Bash or Zsh, there are just a few more steps involved to download the script and add it to your environment. First, switch to your home folder and download the script for version 2.6.0 of WP-CLI:
$ cd ~/
$ curl -O https://raw.githubusercontent.com/wp-cli/wp-cli/v2.6.0/utils/wp-completion.bash
Next, add it to your profile and reload. Bash users can use these commands:
$ echo "source ~/wp-completion.bash" >> ~/.bash_profile
$ source ~/.bash_profile
Zsh users, however, should use these:
$ echo "source ~/wp-completion.bash" >> ~/.zshenv
$ source ~/.zshenv
On a Linux system, instead of sourcing wp-completion.bash
from your ~/.bash_profile
, you need to do so from your ~/.bashrc
. Make sure the wp-completion.bash
file is in your home directory, then run the following commands from the home directory:
cat wp-completion.bash >> .bashrc
source .bashrc
While tab completion to some extent also exists for Windows, to the best of my knowledge it’s not possible to integrate it with third-party tools such as WP-CLI like it is on Mac or Linux. If you know a way to add WP-CLI tab completion on Windows, please reach out in the comments below.
#Creating a WP-CLI Configuration File
The next thing I always do as soon as I have a working WP-CLI installation is to add a configuration file to my $HOME
folder. Configuration files are a fairly advanced topic with lots of interesting functionality that could warrant an entirely separate article. Getting a basic configuration file in place is a great way to reduce the amount of repetitive typing.
Without a configuration file in place, WP-CLI will assume that your working directory is the same as the wp-config.php
file of the actual WordPress site. A lot of times you won’t be in that directory. For example, every time you open up your terminal, you will typically be in your $HOME
folder. Luckily you can supply the --path
parameter to WP-CLI to make it look in the correct folder:
$ wp --path=/Users/eriktorsner/src/path/to/wordpress plugin list
As you can imagine it quickly gets rather tedious to keep typing that initial path variable every single time. To reduce the amount of typing you can add a config file that WP-CLI will use to get path
and other important parameters.
To create this file, open up your favorite text editor and create a file named wp-cli.yml
in your home directory. Add the following line:
path: /Users/eriktorsner/src/path/to/wordpress
You need to adjust that path so it matches where you have—or are planning to put—your local WordPress installation. With this file in place, WP-CLI will automatically know where to look for the WordPress installation so you don’t have to type it every time.
Every time you run the WP-CLI command, it will look for a configuration file to use. There are several potential places to put a config file and there is a specific priority that determines which configuration file is chosen, from highest to lowest priority:
- A file named
wp-cli.local.yml
in the current working directory or upwards - A file named
wp-cli.yml
in the current working directory or upwards - A file named
wp-cli.yml
in your$HOME
folder
Note that the “or upwards” means that, assuming you keep a config file in the root of your WordPress installation, WP-CLI will still be able to find if you have worked yourself down into a subdirectory such as wp-content/uploads/year/month
. It’s also worth knowing that if you want to put your config file somewhere other than your home folder, you can always specify a location using the WP_CLI_CONFIG_PATH
environment variable.
Any parameter you supply via the typed command will override values picked up from a config file, which makes it easy to override values from a config file when needed.
This section has just barely scratched the surface of how incredibly useful the WP-CLI configuration file can be. In a future post, I plan to dig in much deeper and show you how I use them to manage my local WordPress development environments.
#Updating WP-CLI
WP-CLI has the ability to self update. If you installed WP-CLI using the recommended method, you can update it using the update
sub command:
$ sudo wp cli update
On your local development environment, you may want to try out the latest and greatest features of WP-CLI and use the nightly build (but please avoid this on production servers):
$ sudo wp cli update --nightly
If you installed WP-CLI using a package manager, you should always update using the package managers mechanism instead. Updating directly will almost certainly work but I don’t recommend it. You would be robbing the package manager of its chance to know which version is currently installed. That’s never a good thing. Once you have selected your installation method, I suggest you stick with it for updates as well.
#Wrapping Up
If you have followed along in this post, you should now have a working installation of WP-CLI set up with tab completion and a basic configuration file in place. We will start looking at actually getting work done with this tool by digging into plugin management in a future post.
In the meantime, you might want to read our article on WP-CLI packages we can’t live without, or our series on automating local WordPress site setup with scripts.
If you have any questions about how to install WP-CLI, don’t hesitate to let me know in the comments below.
https://deliciousbrains.com/wordpress-cli-packages-review/
I think most developers would agree that WP-CLI (the self-described “command-line interface for WordPress”) is the best thing to happen to WordPress since my-hacks.php
. It is my favorite way to use WP Migrate DB Pro, set up new WordPress sites, control WordPress with CRON, manage plugins, quickly test code, and a whole host of other tasks that are quicker and easier to complete via the CLI or a shell script.
“What,” you might ask, “could possibly be better than WP-CLI?”. “A lot of things…” I would reply, preparing to list off things like
- dogs
- cheeseburgers
- fennec foxes
- when a caterpillar builds its chrysalis on a broom that you left outside and you know that the next time you have to sweep there will be a beautiful, new monarch butterfly flitting around while you work
- puppies
- Bitcoin
- etc…
But then I might catch myself and realize that your question was probably scoped to WordPress development and related tools so I would cough loudly and continue, “*cough* I mean… Packages… For WP-CLI. WP-CLI Packages”
#Free Shipping
The WP-CLI package index is a goldmine of incredibly useful commands. Packages can be installed easily from within WP-CLI with the wp package install [...\]
command, just like you might install an NPM tool using yarn global add [...]
.
While WordPress plugins can provide their own commands to a site that they are installed and activated on, packages have the advantage of being available globally, so if you have a bunch of sites running on the same server you can install a package once and use it on every site. 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).
#Show Me The Goods
There are a ton of great packages in the package index, but here are a few of the ones that I have found to be super useful:
#aaemnnosttv/wp-cli-login-command
This package is not just at the top of my list alphabetically, it’s an incredibly useful little tool that I find myself using much more often than I’m proud of. The wp-cli-login-command
provides a super easy way to log in to a WordPress site without knowing the password or even changing it. Sure, you could run wp user update --pass=Dr1nkM0r30valtine
but that’s the sort of nonsense that got you into this mess in the first place.
Now you can run wp login install --activate
(because this package needs to install its companion plugin on the site) and then wp login create admin
which will generate a “magic login link” that will automatically log you in as your specified user when you click it.
> wp login install --activate; wp login create admin
Success: Companion plugin installed.
Plugin 'wp-cli-login-server' activated.
Success: Activated 1 of 1 plugins.
Success: Magic login link created!
--------------------------------------------------------
https://deliciousbrains.dev/f430b776/a25737-a2fd5c-863013
--------------------------------------------------------
This link will self-destruct in 15 mins, or as soon as it is used; whichever comes first.
Passwords are for suckers.TM
#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 codex 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
db-checkpoint
is another package that does something you could already do by running a few WP-CLI commands or even with WP Migrate DB Pro, but since it’s purpose-built to do this one thing, it just does a way better job.
Here’s the idea: db-checkpoint
(actually, intuitively, the command is dbsnap
) lets you quickly take a snapshot of your database by running wp dbsnap
, after which you can try out a bunch of stupid stuff on your site and then quickly restore it without having to even remember what you named your backup file by running wp dbsnapback
. Presto! Nobody will ever know about all of that stuff you messed up!
> 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
#Oh fork! Why did I think that would ever work!?
> 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!
#Nobody can ever know...
#iandunn/wp-cli-rename-db-prefix
The wp-cli-rename-db-prefix
package is great for any time that you need to change your table prefix for whatever reason. Maybe you still think that it’s a good security practice to make sure that you’re not using wp_
or maybe you’re just trying to use WP Migrate DB Pro to migrate data to a site that uses a different prefix than your dev site. Changing the table prefix manually is a pain and while there are plugins in the repo that rename the WordPress db table prefix, a package just makes way more sense than a plugin that you install, use once, and then uninstall.
> wp rename-db-prefix slartibartfast_
Warning: Use this at your own risk. If something goes wrong, it could break your site. Before running this, make sure to back up your `wp-config.php` file and run `wp db export`.
Are you sure you want to rename devsite.localhost's database prefix from `wp_` to `slartibartfast_`? [y/n] y
Success: Successfully renamed database prefix.
For standard installs (multisite admins are on their own here…), the rename-db-prefix
command really turns this otherwise annoying task into something that barely requires a second thought.
#markri/wp-sec
The wp-sec package is probably something that every WordPress developer should be running regularly on every site they manage, probably with a CRON job that greps the output and emails you when it indicates a vulnerability.
> wp wp-sec check
-----------------------------------------------
Checking core vulnerabilities for version 4.8.5
-----------------------------------------------
No known core vulnerabilities found in version 4.8.5
-------------------------------
Checking plugin vulnerabilities
-------------------------------
Vulnerabilities:
-----------------------------
Plugin: wordpress-seo
Version: 4.9
Vulnerability: Yoast SEO <= 5.7.1 - Unauthenticated Cross-Site Scripting (XSS)
CVE's: 2017-16842
Fixed in: 5.8
------------------------------
Checking theme vulnerabilities
------------------------------
Vulnerabilities:
No known theme vulnerabilities found
-----------------------------------------------
#Packages Are Dead, Long Live Packages!
Okay, so by now you’re totally on board: you’ve installed all of the packages I talked about, you’re browsing the index for more packages you might be able to use, and you’re excited to hear about all of the new packages that are surely being added to the index on a weekly basis, right?!
Here’s the thing though… The WP-CLI Package index is pretty much dead.
TL;DR:
For installing packages, we won’t have an actual “index” in place, we accept any Composer source (git repository, zip file, path to folder, …) as a package, with the added detail that a package identifier of vendor/package will default to the corresponding GitHub repository. […] “Discovery” is then an entirely different problem and will be solved through a separate (potentially third-party) project.
The Package Index is officially deprecated and not currently accepting new packages. There seems to be a plan… to make a plan… to eventually replace it, but other than that we’re currently stuck with what’s currently in the index. New packages can still be installed, albeit a bit more manually by navigating to your package directory (cd $(wp package path)
) and installing a package directly with composer
, but there is currently no way for new packages to be discovered in a centralized place.
While the index is currently host to quite a few great packages, I really hope that the WP-CLI team makes some moves towards creating a new package index so that new packages can be discovered and current package maintainers have a bit more motivation to keep their projects updated.
#Delivery Complete
Long story short: WP-CLI Packages are great and I’d highly recommend browsing the Package Index (even though it’s dead) to find your next invaluable tool. Sure, some of the packages in the index are getting a bit long in the tooth (I even had to remove a few of my recommendations from this post after realizing that they were a bit too broken to recommend), but that doesn’t mean that they’re a total loss. If you find something you like that’s getting a bit buggy, submit a issue or even a PR on the package’s repository.
The best hope we have for a new, improved package index that supports a growing ecosystem of packages is by showing the WP-CLI team and package developers that their packages are being used and an index is necessary.