wp-cli featured

Advanced WP-CLI Commands: Automate and Scale Your WordPress Sites

If you’ve ever spent hours clicking through WordPress admin panels, updating plugins one by one, or performing repetitive tasks that make you want to pull your hair out—you’re not alone. I’ve been there, managing multiple WordPress sites, and feeling like there must be a better way. That’s where WP-CLI (WordPress Command Line Interface) comes into play—a complete game-changer that transforms how you interact with WordPress.

In this comprehensive guide, I’ll walk you through everything you need to know about WP-CLI, from installation to advanced usage, with plenty of real-world examples. By the end, you’ll wonder how you ever managed WordPress without it.

What is WP-CLI and Why Should You Care?

WP-CLI is a command-line tool for managing WordPress that lets you perform almost any administrative or development task without using a web browser. Think of it as having direct access to WordPress’s inner workings through text commands instead of point-and-click interfaces .

The Problems WP-CLI Solves

I’ve experienced these frustrations firsthand:

  • Repetitive Tasks: Updating 50 plugins across multiple sites individually
  • Performance Limitations: Browser-based operations timing out on large operations
  • Development Efficiency: Needing to automate tasks during development workflows
  • Remote Management: Difficulty managing sites when SSH access is all you have

Who Benefits Most from WP-CLI?

User TypeHow WP-CLI HelpsExample Use Cases
DevelopersSpeed up development workflows, automate tasksAutomated testing, database migrations, custom command creation
System AdministratorsManage multiple WordPress installations efficientlyBulk plugin updates, security scans, performance monitoring
Content CreatorsPublish content, manage media, perform quick editsImport large content libraries, bulk image optimization
AgenciesStreamline client site managementStandardized deployment processes, health checks, backups

Getting Started: Installing WP-CLI

The installation process might seem intimidating at first, but I’ll break it down into simple steps. WP-CLI is a PHP application that you download and run from your command line.

System Requirements

Before diving in, ensure your environment meets these minimum requirements :

  • UNIX-like environment (Linux, macOS, FreeBSD, Cygwin); limited support in Windows
  • PHP 5.6 or later
  • WordPress 3.7 or later (older versions may have degraded functionality)

Installation Methods

I’ll cover the most common installation methods, starting with the recommended approach.

This is the simplest method that works across most UNIX-like systems.

# Download the WP-CLI Phar file
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

# Verify it works
php wp-cli.phar --info

# Make it executable and move to your PATH
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

# Verify installation
wp --info

If successful, you’ll see output similar to this :

OS:     Linux 5.10.60.1-microsoft-standard-WSL2 #1 SMP Wed Aug 25 23:20:18 UTC 2021 x86_64
Shell:  /usr/bin/zsh
PHP binary:     /usr/bin/php8.1
PHP version:    8.1.0
php.ini used:   /etc/php/8.1/cli/php.ini
MySQL binary:   /usr/bin/mysql
MySQL version:  mysql Ver 8.0.27-0ubuntu0.20.04.1 for Linux ((Ubuntu))
SQL modes:
WP-CLI root dir:        /home/wp-cli/
WP-CLI vendor dir:      /home/wp-cli/vendor
WP_CLI phar path:
WP-CLI packages dir:    /home/wp-cli/.wp-cli/packages/
WP-CLI global config:
WP-CLI project config:  /home/wp-cli/wp-cli.yml
WP-CLI version: 2.12.0

Method 2: Windows Installation

For Windows users, I recommend using the following PowerShell approach :

# Create directory for WP-CLI
if (!(Test-Path "C:\wp-cli")) { 
    New-Item -ItemType Directory -Path "C:\wp-cli" 
}

# Download WP-CLI
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar" -OutFile "C:\wp-cli\wp-cli.phar"

# Create a batch file to run WP-CLI
$batchFileContent = '@echo off
php "C:\wp-cli\wp-cli.phar" %*'
Set-Content -Path "C:\wp-cli\wp.bat" -Value $batchFileContent

# Add to system PATH
$envPath = [System.Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine)
if ($envPath -notlike "*C:\wp-cli*") { 
    [System.Environment]::SetEnvironmentVariable("Path", "$envPath;C:\wp-cli", [System.EnvironmentVariableTarget]::Machine) 
}

Method 3: Alternative Installation Methods

For those who prefer package managers or alternative approaches:

MethodCommandNotes
Homebrew (macOS)brew install wp-cliEasiest method for Mac users
Composercomposer global require wp-cli/wp-cliBest if you already use Composer
DockerVarious Docker images availableGreat for containerized environments

Updating WP-CLI

Keeping WP-CLI updated is straightforward:

# Update to latest stable version
wp cli update

# For nightly builds (development versions)
wp cli update --nightly

# If installed by root, use sudo
sudo wp cli update

Understanding WP-CLI Command Structure

Before diving into specific commands, it’s important to understand how WP-CLI commands are structured. This knowledge will help you use commands more effectively and even create your own.

Command Anatomy

A WP-CLI command follows this structure:

wp <parent-command> <subcommand> [positional-arguments] [associative-arguments]

Let’s break down an example:

wp plugin install user-switching --activate
  • wp: The WP-CLI executable
  • plugin: Parent command (related to plugin management)
  • install: Subcommand (specific action to perform)
  • user-switching: Positional argument (the plugin slug)
  • --activate: Associative argument (option to activate the plugin after installation)

Types of Arguments

WP-CLI commands accept two types of arguments:

  1. Positional Arguments: Required values in a specific order
    • Example: In wp plugin install <plugin>, <plugin> is a positional argument
    • Multiple values can be accepted using ... (e.g., <plugin>...)
  2. Associative Arguments: Optional parameters with names
    • Always prefixed with --
    • Can accept values with = (e.g., --version=1.0.0)
    • Boolean flags don’t need values (e.g., --activate)

Global Arguments

WP-CLI includes several global arguments that work with all commands :

ArgumentPurpose
--debugDisplay all PHP errors and add extra verbosity
--quietSuppress informational messages
--promptPrompt for missing arguments instead of failing
--version=<version>Specify WordPress version for certain operations

Everyday WP-CLI Commands

Now let’s dive into the commands you’ll use most frequently. I’ll organize these by category with practical examples.

Plugin Management

Plugins are essential to WordPress functionality, and WP-CLI makes managing them incredibly efficient.

# Install and activate a plugin
wp plugin install user-switching --activate

# Install multiple plugins at once
wp plugin install akismet jetpack wordfence --activate

# Update all plugins
wp plugin update --all

# Deactivate a plugin
wp plugin deactivate akismet

# Delete a plugin
wp plugin delete hello-dolly

# List all plugins with status
wp plugin list

# Get plugin information
wp plugin plugin-name --info

Theme Management

Similar to plugins, themes can be managed entirely from the command line:

# Install a theme
wp theme install twentytwentyone --activate

# List installed themes
wp theme list

# Update all themes
wp theme update --all

# Get theme information
wp theme get twentytwentyone

# Delete a theme
wp theme delete twentytwenty

Content Management

Creating and managing content is much faster through WP-CLI:

# Create a new post
wp post create --post_title='Hello World' --post_content='This is my first post created with WP-CLI' --post_status=publish

# List all posts
wp post list --fields=ID,post_title,post_status

# Update a post
wp post update 1 --post_title='Updated Title'

# Delete a post
wp post delete 1

# Generate dummy content (for testing)
wp post generate --count=10

Database Operations

WP-CLI provides powerful database management capabilities:

# Search and replace in the database
wp search-replace 'old-site.com' 'new-site.com' --dry-run

# Actually perform the replacement (remove --dry-run)
wp search-replace 'old-site.com' 'new-site.com'

# Export database
wp db export backup.sql

# Import database
wp db import backup.sql

# Optimize database
wp db optimize

# Repair database
wp db repair

User Management

Managing WordPress users is straightforward with WP-CLI:

# Create a new user
wp user create editor editor@example.com --role=editor --user_pass=strongpassword

# List all users
wp user list

# Update user password
wp user update 1 --user_pass=newstrongpassword

# Delete a user
wp user delete 2 --reassign=1

# Get user information
wp user get 1

Advanced WP-CLI Techniques

Once you’re comfortable with basic commands, you can explore more powerful features that truly transform your WordPress workflow.

Scripting and Automation

One of WP-CLI’s greatest strengths is the ability to create scripts for complex tasks:

#!/bin/bash

# Update all plugins and themes
wp plugin update --all
wp theme update --all

# Clear all caches
wp cache flush

# Optimize database
wp db optimize

# Create backup
wp db export "backup-$(date +%Y%m%d).sql"

echo "WordPress maintenance completed successfully!"

Multisite Network Management

If you manage WordPress multisite installations, WP-CLI provides specialized commands:

# List all sites in network
wp site list

# Create a new site
wp site create --slug=newsite --title="New Site" --email=admin@example.com

# Update a site
wp site update 2 --title="Updated Site Title"

# Delete a site
wp site delete 3

# Perform operation on all sites
wp site list --field=url | xargs -I {} wp plugin update --all --url={}

Performance Profiling

WP-CLI includes performance profiling capabilities:

# Profile WP-CLI performance
wp profile stage --allow-root

# Detailed performance information
wp profile stage --fields=stage,time,query_count,query_time

Extending WP-CLI with Packages

WP-CLI can be extended with third-party packages that add additional functionality. These are similar to WordPress plugins but for WP-CLI itself .

# List available packages
wp package browse

# Install a package
wp package install wp-cli/server-command

# List installed packages
wp package list

# Uninstall a package
wp package uninstall wp-cli/server-command

Popular WP-CLI packages include:

  • wp-cli/server-command: Launch PHP’s built-in web server
  • aaemnnosttv/wp-cli-dotenv-command: Dotenv commands for WP-CLI
  • 10up/mu-migration: Tools for migrating single WordPress instances to multisite

Troubleshooting Common Issues

Even with the best tools, you’ll occasionally encounter issues. Here are solutions to common WP-CLI problems.

Permission Issues

# Error: "Permission denied" when trying to write files
# Solution: Ensure proper permissions on WordPress directories
sudo chown -R www-data:www-data /path/to/wordpress
sudo chmod -R 755 /path/to/wordpress

PHP Version Issues

# Error: "PHP version 5.4 or greater is required"
# Solution: Ensure you're using the correct PHP version
php -v  # Check PHP version
which php  # Check which PHP executable is being used

Database Connection Errors

# Error: "Error establishing database connection"
# Solution: Verify database credentials in wp-config.php
wp config list  # Check database configuration

Memory Limit Issues

# Error: "Allowed memory size exhausted"
# Solution: Increase PHP memory limit
php -d memory_limit=256M wp <command>

Best Practices for WP-CLI Usage

Over the years, I’ve developed several best practices for using WP-CLI effectively:

  1. Always Test in Staging First: Before running commands on production sites, test them in a staging environment to avoid unexpected issues.
  2. Use Dry Runs: For potentially destructive operations, use the --dry-run flag to preview changes: wp search-replace 'old-url' 'new-url' --dry-run
  3. Automate Regular Tasks: Create cron jobs for regular maintenance tasks: # Weekly backup and plugin update 0 3 * * 0 cd /path/to/wordpress && wp db export weekly-backup.sql && wp plugin update --all
  4. Create Aliases for Complex Commands: Add frequently used commands to your shell configuration: # In ~/.bashrc or ~/.zshrc alias wpu='wp plugin update --all && wp theme update --all && wp core update'
  5. Use Version Control: Keep your WP-CLI scripts and custom commands in version control for better collaboration and rollback capabilities.
  6. Document Your Scripts: Add comments to your scripts explaining their purpose and usage:
    bash #!/bin/bash # WordPress maintenance script # Updates all plugins, themes, and core, then creates a backup # Usage: ./maintenance.sh

Real-World WP-CLI Use Cases

To illustrate the power of WP-CLI, here are some real-world scenarios where I’ve found it invaluable:

Scenario 1: Emergency Plugin Rollback

When a plugin update breaks your site, WP-CLI can save you quickly:

# Identify the problematic plugin
wp plugin list --status=active

# Deactivate the problematic plugin
wp plugin deactivate problematic-plugin

# If needed, rollback to previous version
wp plugin install problematic-plugin --version=1.0.0 --force

Scenario 2: Bulk Content Migration

Moving content between sites becomes much simpler:

# Export all posts from old site
wp post list --format=ids | xargs -I {} wp post export {} --dir=exports/

# Import posts to new site
for file in exports/*.xml; do
    wp import "$file" --authors=create
done

Scenario 3: Security Audit

Performing a quick security check across multiple sites:

#!/bin/bash
# Security audit script

# Check for vulnerable plugins
echo "Checking for vulnerable plugins..."
wp plugin list --update=available

# Check WordPress version
echo "Checking WordPress version..."
wp core version

# Check for file modifications
echo "Checking for file modifications..."
wp core verify-checksums

# Create backup
echo "Creating backup..."
wp db export security-audit-backup.sql

echo "Security audit completed."

WP-CLI vs. Traditional Admin Panel

To help you understand the efficiency gains, here’s a comparison of common tasks:

TaskAdmin PanelWP-CLITime Savings
Update 50 PluginsClick each plugin individually (5-10 minutes)wp plugin update --all (30 seconds)90-95%
Search and Replace URLUse plugin or database tool (2-3 minutes)wp search-replace 'old' 'new' (10 seconds)90%
Create 50 Test PostsManual entry (1-2 hours)wp post generate --count=50 (5 seconds)99%
Database BackupExport via phpMyAdmin (3-5 minutes)wp db export backup.sql (30 seconds)85-90%
Check Core VersionDashboard > Updates (30 seconds)wp core version (2 seconds)93%

WrapUP

Learning WP-CLI might seem like a steep learning curve at first, but the productivity gains are well worth the investment. I’ve transformed from someone who dreaded maintenance tasks to someone who actually enjoys them—simply because I can accomplish in minutes what used to take hours.

The key is to start small: begin with basic plugin and theme management, gradually incorporate more advanced commands as you become comfortable. Before you know it, you’ll be creating custom scripts and automating workflows you never thought possible.

Whether you’re a developer managing multiple client sites, a system administrator overseeing numerous installations, or a site owner looking to save time, WP-CLI is an essential tool in your WordPress toolkit. The efficiency, automation, and precision it offers are simply unmatched by traditional admin panel methods.

So why not give it a try? Start with the basic commands in this guide, explore the extensive documentation, and join the thousands of WordPress professionals who have already transformed their workflows with WP-CLI.

Additional Resources

For those looking to dive deeper, here are three excellent resources to continue your WP-CLI journey:

  1. Official WP-CLI Documentation – The comprehensive guide to all WP-CLI commands and features
  2. WP-CLI Commands Reference – Complete listing of all available WP-CLI commands with usage examples
  3. WP-CLI GitHub Repository – Source code and development information for those interested in contributing

The WordPress command line interface has revolutionized how I manage websites, and I’m confident it will do the same for you.

FAQs

What is WP-CLI, and why should I use it?

WP-CLI (WordPress Command Line Interface) is a tool that lets you manage your WordPress website using commands in a terminal instead of clicking through the WordPress admin panel. It’s faster, more efficient, and great for tasks like updating plugins, managing users, or even troubleshooting issues without logging in to your website.

Do I need programming skills to use WP-CLI?

Not at all! While some basic command-line knowledge helps, most WP-CLI commands are simple and easy to understand. For example, wp plugin update --all is just like clicking “Update All” in your WordPress dashboard—but much faster.

Can I use WP-CLI on any WordPress site?

Yes! As long as your site is hosted on a server that supports PHP and you have command-line access (like SSH), you can use WP-CLI. It works on Linux, macOS, and even Windows (with some setup).

Is WP-CLI safe to use on a live website?

Yes, but you should be careful. Always test commands on a staging site first, especially for destructive actions like deleting plugins or modifying the database. Using the --dry-run flag can also help you preview changes before applying them.

Can I automate tasks with WP-CLI?

Absolutely! You can create scripts (like shell scripts) to run multiple WP-CLI commands automatically. For example, you could make a script that updates all plugins, clears the cache, and creates a backup—all in one go.

What’s the difference between WP-CLI and the WordPress admin?

The WordPress admin is graphical (you click buttons), while WP-CLI is text-based (you type commands). WP-CLI is faster, works better for repetitive tasks, and can do things (like bulk operations) that are harder in the admin panel.

Can I undo a WP-CLI command if I make a mistake?

It depends on the command. Some actions, like deleting a plugin, can’t be easily undone unless you have a backup. Always use --dry-run first to preview changes, and keep backups of your site and database.

Does WP-CLI work with multisite installations?

Yes! WP-CLI has special commands for managing WordPress multisite networks, like creating new sites (wp site create) or performing actions across all sites in a network.

Vivek Kumar

Vivek Kumar

Full Stack Developer
Active since May 2025
34 Posts

Full-stack developer who loves building scalable and efficient web applications. I enjoy exploring new technologies, creating seamless user experiences, and writing clean, maintainable code that brings ideas to life.

You May Also Like

More From Author

4 1 vote
Would You Like to Rate US
Subscribe
Notify of
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments