WP-CLI: The Ultimate Command Line Tool for WordPress

Every WordPress developer reaches the same point: navigating the admin dashboard for repetitive operations becomes tedious. Updating 40 plugins one by one through the UI. Running a database search-replace for a migration. Creating dozens of test posts. Managing WordPress on 20 client sites.

WP-CLI (WordPress Command-Line Interface) solves all of this. It's a command-line tool that lets you interact with WordPress through your terminal — faster, scriptable, and automatable in ways the admin UI never can be.

This guide covers everything from installation to the essential commands every WordPress developer should have in their toolkit — plus how to build custom WP-CLI commands for your own automation needs.

What Is WP-CLI?

WP-CLI is the official command-line interface for WordPress. It's built by the WordPress community, maintained as an open-source project, and used by developers, DevOps engineers, and site administrators worldwide.

With WP-CLI you can:

  • Update WordPress core, plugins, and themes from the terminal
  • Run database operations (search-replace, export, import, optimize)
  • Create, read, update, and delete any WordPress content
  • Manage users, options, and site configuration
  • Perform WordPress migrations
  • Run custom PHP code in the WordPress context
  • Automate repetitive tasks via shell scripts
  • Manage remote WordPress installations over SSH
01
Installing WP-CLI

On macOS/Linux:

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

# Test the download works
php wp-cli.phar --info

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

# Verify installation
wp --info

On Windows:

Use Windows Subsystem for Linux (WSL) for the best experience, then follow the Linux instructions above. Or download wp-cli.phar directly and run it as php wp-cli.phar from your WordPress directory.

On Hosting Providers:

Many managed hosts include WP-CLI pre-installed:

Host WP-CLI Access
KinstaAvailable via SSH, no installation needed
CloudwaysAvailable after SSH access, use wp
WP EngineAvailable in their SSH gateway

Check your host's documentation — SSH access is typically required.

On Local Development (Local App):

Local (by Flywheel) includes a WP-CLI integration: right-click any site → Open Site Shell → WP-CLI is ready with the correct site context.

Pro Tip: WP-CLI follows the pattern wp <command> <subcommand> [--option=value]. You must run it from your WordPress installation's root directory (where wp-config.php lives), or specify the path with wp --path=/var/www/html.
02
Core, Plugin & Theme Management

WordPress Core:

Bash
# Check current version
wp core version

# Check if update available
wp core check-update

# Update WordPress core
wp core update

# Update database after core update
wp core update-db

# Install WordPress (non-interactive)
wp core install \
  --url="https://yourdomain.com" \
  --title="My Site" \
  --admin_user="admin_username" \
  --admin_password="strong_password" \
  --admin_email="[email protected]"

Plugin Management:

Bash
# List all installed plugins
wp plugin list

# List plugins with update available
wp plugin list --update=available

# Install a plugin
wp plugin install wordfence

# Install a specific version
wp plugin install woocommerce --version=8.0.0

# Activate / Deactivate
wp plugin activate wordfence
wp plugin deactivate wordfence

# Update a specific plugin
wp plugin update woocommerce

# Update all plugins
wp plugin update --all

# Delete a plugin (deactivate + delete)
wp plugin delete hello-dolly

# Bulk install and activate multiple plugins
wp plugin install rank-math-seo updraftplus wordfence --activate

Theme Management:

Bash
# List themes
wp theme list

# Install and activate a theme
wp theme install astra --activate

# Update all themes
wp theme update --all

# Get current active theme
wp theme status
03
Database Operations

Database operations are where WP-CLI truly shines — operations that take minutes in phpMyAdmin take seconds.

Bash
# Export database
wp db export backup.sql

# Export and compress
wp db export - | gzip > backup-$(date +%Y%m%d).sql.gz

# Import database
wp db import backup.sql

# Search and replace URLs (essential for migrations)
wp search-replace 'http://old-domain.com' 'https://new-domain.com' --all-tables

# Dry run first — see what would change without making changes
wp search-replace 'http://old-domain.com' 'https://new-domain.com' --all-tables --dry-run

# Search-replace with report
wp search-replace 'http://old-domain.com' 'https://new-domain.com' --all-tables --report-changed-only

# Optimize all database tables
wp db optimize

# Check all database tables for errors
wp db check

# Repair database tables
wp db repair

# Show database table sizes
wp db tables --size

# Run an arbitrary SQL query
wp db query "SELECT COUNT(*) FROM wp_posts WHERE post_status = 'publish'"
Important: Always use --dry-run before running search-replace on a production database. Always export a backup with wp db export before any destructive database operation.
04
User Management & Options

User Management:

Bash
# List all users
wp user list

# List admin users only
wp user list --role=administrator

# Create a new user
wp user create john_doe [email protected] \
  --role=editor \
  --display_name="John Doe"

# Get a new generated password for a user
wp user reset-password john_doe --skip-email

# Update user role
wp user set-role 5 administrator

# Delete a user (reassign content to another user)
wp user delete 5 --reassign=1

# Generate test users
wp user generate --count=10 --role=subscriber

Options and Configuration:

Bash
# Get any option value
wp option get siteurl
wp option get blogname

# Update an option
wp option update blogdescription "Professional WordPress Development"

# Get all options matching a pattern
wp option list --search="*woocommerce*" --format=table

# Add a new option
wp option add my_plugin_setting "default_value"

# Delete an option
wp option delete my_plugin_setting
05
Posts, Cache & Cron Management

Post and Content Management:

Bash
# List posts
wp post list --post_type=post --posts_per_page=10

# Create a post
wp post create \
  --post_type=post \
  --post_title="Test Post via CLI" \
  --post_content="Content here." \
  --post_status=publish

# Update a post
wp post update 42 --post_title="Updated Title"

# Get / Set post meta
wp post meta get 42 _thumbnail_id
wp post meta set 42 my_custom_field "custom_value"

# Bulk delete trashed posts
wp post delete $(wp post list --post_type=post --post_status=trash --format=ids)

# Generate 50 test posts
wp post generate --count=50 --post_type=post --post_status=publish

Cache Management:

Bash
# Flush the object cache (Redis, Memcached)
wp cache flush

# Clear WP Rocket cache
wp rocket clean --confirm

# Flush expired transients from database
wp transient delete --expired

# Flush all transients
wp transient delete --all

Cron Management:

Bash
# List scheduled cron events
wp cron event list

# Run all due cron events (useful for testing)
wp cron event run --due-now

# Schedule a cron event
wp cron event schedule my_event now hourly

# Delete a cron event
wp cron event delete my_event
06
Creating Custom WP-CLI Commands

For repetitive tasks specific to your project, create custom WP-CLI commands. Register in a plugin or functions.php:

PHP
if ( defined( 'WP_CLI' ) && WP_CLI ) {
    
    class My_Site_CLI {
        
        /**
         * Import posts from a CSV file.
         *
         * ## OPTIONS
         *
         * <file>
         * : Path to the CSV file.
         *
         * [--dry-run]
         * : Preview what would be imported without making changes.
         *
         * ## EXAMPLES
         *
         *     wp mysite import-posts /path/to/posts.csv
         *     wp mysite import-posts /path/to/posts.csv --dry-run
         *
         * @when after_wp_load
         */
        public function import_posts( $args, $assoc_args ) {
            list( $file ) = $args;
            $dry_run = WP_CLI\Utils\get_flag_value(
                $assoc_args, 'dry-run', false
            );

            if ( ! file_exists( $file ) ) {
                WP_CLI::error( "File not found: {$file}" );
            }

            $handle  = fopen( $file, 'r' );
            $headers = fgetcsv( $handle );
            $count   = 0;

            while ( ( $row = fgetcsv( $handle ) ) !== false ) {
                $data = array_combine( $headers, $row );

                if ( $dry_run ) {
                    WP_CLI::log(
                        "Would import: {$data['title']}"
                    );
                } else {
                    $post_id = wp_insert_post( array(
                        'post_title'   =>
                            sanitize_text_field( $data['title'] ),
                        'post_content' =>
                            wp_kses_post( $data['content'] ),
                        'post_status'  => 'publish',
                    ) );

                    if ( is_wp_error( $post_id ) ) {
                        WP_CLI::warning(
                            "Failed: {$data['title']}"
                        );
                    } else {
                        $count++;
                    }
                }
            }

            fclose( $handle );

            if ( $dry_run ) {
                WP_CLI::success( "Dry run complete." );
            } else {
                WP_CLI::success(
                    "Imported {$count} posts."
                );
            }
        }
    }

    WP_CLI::add_command( 'mysite', 'My_Site_CLI' );
}

Usage:

Bash
wp mysite import-posts /path/to/posts.csv --dry-run
wp mysite import-posts /path/to/posts.csv

WP-CLI in Deployment Scripts

WP-CLI shines in deployment automation. A typical deployment script:

Bash — deploy.sh
#!/bin/bash
# deploy.sh - WordPress deployment script

set -e  # Stop on any error

echo "=== Starting WordPress Deployment ==="

# Enter WordPress directory
cd /var/www/html

# Put site in maintenance mode
wp maintenance-mode activate

# Backup database
wp db export backups/pre-deploy-$(date +%Y%m%d-%H%M%S).sql

# Update WordPress core
wp core update
wp core update-db

# Update all plugins
wp plugin update --all

# Update all themes
wp theme update --all

# Search and replace if URL changed
# wp search-replace 'http://staging.site.com' 'https://site.com' --all-tables

# Flush caches
wp cache flush
wp transient delete --expired

# Remove maintenance mode
wp maintenance-mode deactivate

echo "=== Deployment Complete ==="
wp core version
Pro Tip: Use set -e at the top of deployment scripts so the script stops immediately if any command fails — preventing partial deployments.

Quick Reference: Essential Commands

Task Command
Check WordPress versionwp core version
Update all pluginswp plugin update --all
Export databasewp db export backup.sql
URL search-replacewp search-replace 'old' 'new' --all-tables
Create an admin userwp user create admin [email protected] --role=administrator
Flush object cachewp cache flush
Generate test postswp post generate --count=50
Run due cron eventswp cron event run --due-now
Get site URLwp option get siteurl
List active pluginswp plugin list --status=active

Frequently Asked Questions

Q: Can I use WP-CLI on shared hosting?
A: It depends on whether your host provides SSH access. Many shared hosts don't — check your hosting documentation. SiteGround, Cloudways, and most managed hosts do. Basic shared hosting often doesn't.
Q: Is WP-CLI safe to run on production sites?
A: Yes, with appropriate care. Always back up before destructive operations (wp db export before any search-replace or database modification). Use --dry-run flags where available to preview changes. The --skip-themes and --skip-plugins flags can isolate WP-CLI from theme/plugin conflicts.
Q: How do I run WP-CLI on a remote server?
A: Via SSH. If you have SSH access: ssh user@server "cd /path/to/wordpress && wp plugin update --all". Or configure a WP-CLI alias in ~/.wp-cli/config.yml for frequently used remote sites.

Final Thoughts

WP-CLI is one of those tools that transforms how you work with WordPress. The first time you update all plugins on 15 client sites with a single script, or perform a database search-replace across 50,000 records in 3 seconds, you'll wonder how you managed without it.

Install it, learn the core commands, then start building your own automation scripts.

Contact us for professional WordPress development and DevOps automation
Views: 177