How to Use the WordPress Command Line Interface – WP-CLI Tutorial
As an experienced WordPress developer, you know that efficient workflows are essential for managing sites and delivering projects on time. While the WordPress admin dashboard works well for many basic tasks, power users and advanced developers need more flexible, scriptable tools for streamlined site management. Enter WP-CLI – the WordPress Command Line Interface – an incredibly powerful tool for controlling nearly every aspect of a WordPress installation right from your terminal.
In this comprehensive tutorial, we‘ll dive deep into WP-CLI and cover everything from basic installation to advanced usage, helpful packages, and workflow integration tips. Whether you‘re a WordPress developer, site admin, or power user, WP-CLI will revolutionize how you manage WordPress sites.
What is WP-CLI?
WP-CLI is a command line tool used to manage WordPress installations from a terminal, without needing to use a web browser. It provides a rich set of commands for tasks like plugin management, user administration, database manipulation, content generation, and much more.
WP-CLI is built with PHP and designed to integrate seamlessly with WordPress‘s core functionality and APIs. This means developers can use WP-CLI to script and automate almost any WordPress admin task, dramatically speeding up site management workflows.
Key Benefits of WP-CLI
So why should WordPress developers learn and use WP-CLI? Here are some of the key benefits:
- Speed – Execute complex WordPress operations with single terminal commands
- Precision – Perform risky database and server operations with full control
- Automation – Write scripts to automate repetitive setup and maintenance tasks
- Remote control – Manage WordPress sites remotely on any server/environment
- Workflow integration – Integrate with tools like Git, Composer, Docker, and CI/CD pipelines
In short, if you‘re spending significant time managing WordPress sites, WP-CLI will make you faster, more efficient, and more capable of handling advanced customizations and server operations.
WordPress & WP-CLI Adoption Stats
To underscore just how ubiquitous WP-CLI has become, let‘s look at some recent statistics:
- WordPress now powers over 43% of all websites (W3Techs)
- WP-CLI has been downloaded over 21 million times (WordPress.org)
- Over 61 million WordPress sites are managed with WP-CLI (WordPress.org)
- WP-CLI averages over 30,000 new downloads each day (WordPress.org)
The widespread adoption of WP-CLI reflects its stability, utility, and importance in the professional WordPress ecosystem. Knowing WP-CLI has become an essential skill for WordPress developers.
Installing WP-CLI
Before we explore WP-CLI‘s commands and usage examples, let‘s walk through the installation process. We‘ll be installing WP-CLI on a Unix-like system (Linux/macOS).
System Requirements
WP-CLI has a few key requirements:
- Unix-like OS (Linux, macOS, Cygwin, Bash for Windows)
- PHP 7.4 or newer (with mysqli and mysql PHP extensions)
- WordPress 3.7 or newer
For this tutorial, we assume you already have a local WordPress development environment running that meets the above requirements.
Downloading WP-CLI
The recommended way to install WP-CLI is by downloading its phar file. Open a terminal and use cURL or Wget to download wp-cli.phar:
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
Installing Globally
For easier usage, it‘s best to install wp-cli.phar globally on your system. This involves making the file executable and moving it somewhere in your PATH.
First, check wp-cli.phar works:
php wp-cli.phar --info
Make wp-cli.phar executable:
chmod +x wp-cli.phar
Move the file to /usr/local/bin and rename to wp:
sudo mv wp-cli.phar /usr/local/bin/wp
Now test that WP-CLI is installed properly by running:
wp --info
You should see output like:
OS: Linux 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64
Shell: /usr/bin/zsh
PHP binary: /usr/bin/php8.1
PHP version: 8.1.2-1ubuntu2.8
php.ini used: /etc/php/8.1/cli/php.ini
MySQL binary: /usr/bin/mysql
MySQL version: mysql Ver 8.0.31-0ubuntu0.20.04.2 for Linux on x86_64 ((Ubuntu))
SQL modes: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
WP-CLI root dir: phar://wp-cli.phar
WP-CLI vendor dir: phar://wp-cli.phar/vendor
WP_CLI phar path: /home/jsmith
WP-CLI packages dir: /home/jsmith/.wp-cli/packages/
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.7.1
With WP-CLI installed, you‘re ready to start using it to manage WordPress!
Note: WP-CLI requires quite a few PHP modules and extensions. If you‘re missing any, wp –info will alert you and provide instructions for installing them.
WP-CLI Command Overview
WP-CLI provides a huge number of commands for managing WordPress. We‘ll cover some of the most important and frequently used ones here.
Note: All WP-CLI commands must be run from a WordPress installation‘s root directory.
Getting Help
To see all available WP-CLI commands, simply run:
wp help
And to get help for a specific command, run:
wp help <command>
WP-CLI‘s built-in documentation is excellent, so be sure to consult it liberally as you learn the tool.
Checking Site Status
Get an overview of a WordPress site‘s key details and stats with:
wp site info
wp site status
This will display things like:
- WordPress version, name, URL, title
- Active theme and plugins
- User counts per role
- Post counts per type
- Database table sizes/rows
Great for quickly learning about an unfamiliar WordPress install.
Managing the Database
Easily export/import the WordPress database from the command line:
# Create a gzipped database export
wp db export --add-drop-table --result-file=backup.sql
gzip backup.sql
# Import from a gzipped SQL dump
gzip -d backup.sql.gz
wp db import backup.sql
Some other handy database commands:
# Reset the database
wp db reset --yes
# Search/replace strings in the database
wp search-replace "http://example.dev" "https://example.com" --precise --recurse-objects --all-tables
# Run an arbitrary SQL query
wp db query "SELECT ID, post_title FROM wp_posts LIMIT 5"
Warning: Always backup the database before performing potentially destructive operations!
Managing Themes & Plugins
Some quick examples of installing and activating themes/plugins:
# Install a theme from wordpress.org
wp theme install neve --activate
# Install and activate a plugin
wp plugin install wordpress-seo --activate
# Activate an installed plugin
wp plugin activate akismet
# Install a plugin from a ZIP file
wp plugin install ~/downloads/wp-graphql.zip --activate
# Update all active plugins
wp plugin update --all
You can also verify the checksum of WordPress.org themes/plugins:
wp core verify-checksums --type=themes
wp core verify-checksums --type=plugins
This helps ensure you‘re getting official WP themes/plugins and not something malicious.
Managing Users
Create, modify, delete, and list WordPress users right from your terminal:
# Create a user
wp user create bob [email protected] --role=author
# Update a user‘s display name
wp user update 12345 --display_name="Bob Smith"
# Delete a user
wp user delete 12345 --reassign=567
# List users
wp user list --role=administrator
# Generate a new password for a user
wp user reset-password 12345
You can also quickly log in as any user for testing:
wp user login bob
So much faster than clicking around the Users admin screens!
Creating Content
WP-CLI makes generating placeholder content a breeze:
# Generate 10 random posts
wp post generate --count=10
# Create a new page
wp post create --post_type=page --post_title="Contact Us" --post_status=publish
# Update a post‘s metadata
wp post meta update 12345 _thumbnail_id 6789
And quickly assign posts to categories and tags:
wp post term add 12345 category "Announcements"
wp post term add 12345 post_tag "Featured"
Perfect for setting up new WordPress sites or testing themes.
Updating WordPress Core
You can even handle WordPress core updates with:
# Check for new WordPress versions
wp core check-update
# Update WordPress to latest version
wp core update
# Update WordPress to a specific version
wp core update --version=5.9.1
# Update WordPress nightly build
wp core update --nightly
The –dry-run flag lets you safely test updates without applying them.
Advanced WP-CLI Usage
Hopefully the command samples above highlight how fast and powerful WP-CLI can be. Now let‘s look at some more advanced ways to integrate WP-CLI into WordPress development workflows.
Writing Custom Commands
One of WP-CLI‘s best features is its robust framework for writing custom commands. This allows developers to extend WP-CLI with their own site or project-specific commands.
For example, here‘s a custom command to display the number of users with a specific role:
/**
* Get number of users with a specific role.
*
* ## OPTIONS
* <role>
* : The role to check (e.g. administrator, editor)
*
* ## EXAMPLES
*
* # Get number of administrator users
* wp user-role-count administrator
*
* # Get number of editor users
* wp user-role-count editor
*/
function user_role_count( $args, $assoc_args ) {
$role = array_shift( $args );
$users = get_users( [ ‘role‘ => $role ] );
WP_CLI::log( ‘There are ‘ . count( $users ) . ‘ ‘ . $role . ‘ users.‘ );
}
WP_CLI::add_command( ‘user-role-count‘, ‘user_role_count‘ );
Put that code in a file like wp-user-role-count.php and require it in your wp-config.php file. You can then run:
wp user-role-count administrator
And get output like:
There are 6 administrator users.
Custom commands are extremely useful for automating workflows unique to your sites or development team. And WP-CLI‘s API makes creating them quite approachable.
Useful Community Packages
In addition to custom commands, WP-CLI boasts a rich ecosystem of community packages that extend its functionality. Here are some of the most popular and useful ones:
- wp-cli/find-command – Instantly search for WordPress content from the command line
- aaemnnosttv/wp-cli-dotenv-command – Inject variables into a .env file
- wp-cli/dist-archive-command – Create a distribution archive based on a manifest
- schlessera/wp-cli-faker – Generate fake WordPress content using the Faker PHP library
Browse the official package index to see what‘s available. Including WP-CLI packages in your WordPress projects and build tools is an excellent way to customize and extend your development workflows.
Real-world WP-CLI Automation Examples
Finally, let‘s look at some real-world case studies and examples of WP-CLI in action to automate advanced WordPress ops:
- Using WP-CLI to automate WordPress core updates
- Automatically deploying a WordPress site with Capistrano and WP-CLI
- How Spotify uses WP-CLI to update their engineering blogs
- Using WP-CLI within Laravel Forge workflows
These posts illustrate how WP-CLI can slot neatly into broader WordPress deployment, testing, and server management processes. But the possibilities are truly endless!
Tips & Best Practices
As you use WP-CLI more and integrate it into your day-to-day WordPress ops, keep these tips and best practices in mind:
- Use –prompt for destructive operations – WP-CLI will intelligently prompt you to confirm risky things like dropping all database tables
- Define site aliases – Create ~/.wp-cli/config.yml files to alias different remote WordPress sites for easier management
- Chain commands with && – Execute multiple commands in sequence by joining them with &&
- Pipe data between commands – Use | to pass the output of one wp command into another wp command or shell utility
- Create custom profiles – Create ~/.wp-cli/profiles to quickly register groups of command arguments you use frequently
- Automate everything you can! – If you‘re running a command more than a few times, consider scripting it for reuse
- Use –skip-plugins/themes for speed – Skip loading all plugins/themes to speed up certain operations
- Keep backups and logs – Always store a trail of your WP-CLI operations, scripts, SQL dumps, etc.
- Contribute back! – If you write a useful custom command or script, considering sharing it back with the WP-CLI community
Above all, be curious and experiment! WP-CLI rewards an inquisitive, tinkering approach to WordPress management.
Conclusion
Hopefully this tutorial has demonstrated how the WordPress Command Line Interface can revolutionize your WordPress development workflows. With its intuitive commands, extensible interface, and active community, WP-CLI arms WordPress experts with a powerful tool for site management, maintenance, testing, and deployment.
While WP-CLI is objectively more complex than the WordPress admin GUI, it offers unparalleled speed, scriptability, and precision for advanced WordPress operations. And its gentle learning curve means you can be productive with it quickly, while gradually mastering more advanced usage over time.
So crack open your terminal and start exploring all that WP-CLI has to offer! I think you‘ll find it an indispensable addition to your WordPress development toolkit.