Optimize WordPress Performance with WP-CLI: 15 Proven Techniques

Website performance directly impacts user experience, search engine rankings, and conversion rates. WP-CLI provides powerful tools to diagnose performance bottlenecks and implement optimizations efficiently, making it essential for developers managing high-traffic WordPress sites.

Why Use WP-CLI for Performance Optimization

Traditional WordPress performance optimization through the dashboard is time-consuming and often incomplete. WP-CLI enables systematic, repeatable optimizations that can be automated, scripted, and applied across multiple sites simultaneously.

The command-line approach offers distinct advantages: batch processing of operations, precise control over optimization tasks, ability to schedule regular maintenance, detailed logging of changes, and integration with deployment pipelines. These capabilities make WP-CLI indispensable for professional WordPress performance management.

1. Database Optimization and Cleanup

Database bloat significantly impacts query performance. Over time, WordPress databases accumulate revisions, spam comments, orphaned metadata, and expired transients that slow down queries.

# Check database size before optimization
wp db size --tables

# Optimize all database tables
wp db optimize

# Remove post revisions older than 30 days
wp post delete $(wp post list --post_type=revision --format=ids --date_query='[{"before":"30 days ago"}]') --force

# Clean up spam and trashed comments
wp comment delete $(wp comment list --status=spam --format=ids) --force
wp comment delete $(wp comment list --status=trash --format=ids) --force

# Remove orphaned post metadata
wp db query "DELETE pm FROM wp_postmeta pm LEFT JOIN wp_posts wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL"

# Clean expired transients
wp transient delete --expired

# Remove all transients (use cautiously)
wp transient delete --all

Create a comprehensive database cleanup script:

#!/bin/bash
# db-cleanup.sh - Comprehensive database optimization

WP_PATH="/var/www/html"

echo "Starting database optimization..."

# Backup before cleanup
wp --path="$WP_PATH" db export backup-pre-cleanup-$(date +%Y%m%d).sql

# Get initial database size
INITIAL_SIZE=$(wp --path="$WP_PATH" db size --human-readable --format=json | jq -r '.Size')
echo "Initial database size: $INITIAL_SIZE"

# Remove old post revisions (keep last 5 for each post)
wp --path="$WP_PATH" config set WP_POST_REVISIONS 5 --type=constant

# Delete old auto-drafts
wp --path="$WP_PATH" post delete $(wp --path="$WP_PATH" post list --post_status=auto-draft --format=ids) --force

# Clean comments
wp --path="$WP_PATH" comment delete $(wp --path="$WP_PATH" comment list --status=spam --format=ids) --force
wp --path="$WP_PATH" comment delete $(wp --path="$WP_PATH" comment list --status=trash --format=ids) --force

# Remove orphaned metadata
wp --path="$WP_PATH" db query "DELETE FROM wp_commentmeta WHERE comment_id NOT IN (SELECT comment_ID FROM wp_comments)"
wp --path="$WP_PATH" db query "DELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT ID FROM wp_posts)"
wp --path="$WP_PATH" db query "DELETE FROM wp_termmeta WHERE term_id NOT IN (SELECT term_id FROM wp_terms)"

# Clean transients
wp --path="$WP_PATH" transient delete --expired

# Optimize tables
wp --path="$WP_PATH" db optimize

# Get final database size
FINAL_SIZE=$(wp --path="$WP_PATH" db size --human-readable --format=json | jq -r '.Size')
echo "Final database size: $FINAL_SIZE"
echo "Database optimization completed"

2. Cache Management

Effective cache management is crucial for performance. WP-CLI provides commands to manage object cache, page cache, and opcode cache.

# Flush object cache (Redis, Memcached, etc.)
wp cache flush

# Test cache functionality
wp cache set test_key test_value 300
wp cache get test_key

# For sites using Redis
wp redis info

# Clear page cache for specific plugins
# W3 Total Cache
wp w3-total-cache flush all

# WP Super Cache
wp cache flush

# Clear cache for specific pages/posts
wp transient delete --all

Implement intelligent cache warming:

#!/bin/bash
# cache-warm.sh - Warm up cache for important pages

SITE_URL="https://example.com"
WP_PATH="/var/www/html"

# Get list of published posts and pages
URLS=$(wp --path="$WP_PATH" post list --post_type=post,page --post_status=publish --field=url)

# Warm cache by requesting each URL
for url in $URLS; do
    echo "Warming cache: $url"
    curl -s -o /dev/null "$url"
    sleep 0.5  # Avoid overwhelming server
done

# Warm up homepage and key pages
curl -s -o /dev/null "$SITE_URL"
curl -s -o /dev/null "$SITE_URL/about"
curl -s -o /dev/null "$SITE_URL/contact"

echo "Cache warming completed"

3. Image Optimization

Images often account for the majority of page weight. WP-CLI can help automate image optimization tasks.

# Regenerate thumbnails for all images
wp media regenerate --yes

# Regenerate only missing thumbnails
wp media regenerate --only-missing --yes

# Regenerate images uploaded in specific timeframe
wp media regenerate --yes $(wp post list --post_type=attachment --format=ids --post_mime_type=image --year=2024)

# Install and configure image optimization plugin via CLI
wp plugin install ewww-image-optimizer --activate
wp option update ewww_image_optimizer_cloud_key 'YOUR_API_KEY'

# Bulk optimize existing images
wp ewwwio optimize all

4. Plugin Performance Audit

Identify and manage plugins that impact performance negatively.

# List all active plugins
wp plugin list --status=active

# Check for plugin updates
wp plugin list --update=available

# Deactivate unused plugins
wp plugin deactivate plugin-slug

# Remove unused plugins completely
wp plugin delete plugin-slug

# Identify plugins loading on every page
wp plugin list --status=active --field=name | while read plugin; do
    echo "Checking: $plugin"
    wp plugin path $plugin
done

Create a plugin performance audit script:

#!/bin/bash
# plugin-audit.sh - Audit plugin performance impact

WP_PATH="/var/www/html"

echo "=== Plugin Performance Audit ==="

# List active plugins with version info
echo -e "\nActive Plugins:"
wp --path="$WP_PATH" plugin list --status=active --fields=name,version,update,auto_update

# Check for outdated plugins
echo -e "\nPlugins requiring updates:"
wp --path="$WP_PATH" plugin list --update=available --fields=name,version,update_version

# Identify plugins with known performance issues
echo -e "\nChecking for resource-intensive plugins..."

# Get plugin file sizes
for plugin in $(wp --path="$WP_PATH" plugin list --status=active --field=name); do
    PLUGIN_PATH=$(wp --path="$WP_PATH" plugin path $plugin)
    SIZE=$(du -sh "$PLUGIN_PATH" 2>/dev/null | cut -f1)
    echo "$plugin: $SIZE"
done | sort -h

5. Autoload Optimization

Excessive autoloaded options slow down every WordPress request. Optimize autoloaded data to reduce overhead.

# Check autoload size
wp db query "SELECT SUM(LENGTH(option_value)) as autoload_size FROM wp_options WHERE autoload='yes'"

# List large autoloaded options
wp db query "SELECT option_name, LENGTH(option_value) as size FROM wp_options WHERE autoload='yes' ORDER BY size DESC LIMIT 20"

# Convert large options to non-autoload
wp option update large_option_name 'value' --autoload=no

# Remove obsolete autoloaded options
wp db query "DELETE FROM wp_options WHERE autoload='yes' AND option_name LIKE '%_transient_%'"

6. Query Monitoring and Optimization

Monitor database queries to identify performance bottlenecks.

# Enable query logging (for development)
wp config set SAVEQUERIES true --raw

# Check for slow queries in production
wp db query "SELECT * FROM information_schema.processlist WHERE command != 'Sleep' AND time > 5"

# Add database indexes for custom queries
wp db query "CREATE INDEX idx_meta_key_value ON wp_postmeta(meta_key, meta_value(100))"

# Analyze table structure
wp db query "SHOW INDEX FROM wp_posts"
wp db query "SHOW INDEX FROM wp_postmeta"

7. Content Delivery Network Integration

Configure CDN settings programmatically for consistent deployment.

# Update site URL for CDN
wp search-replace 'https://example.com/wp-content' 'https://cdn.example.com/wp-content' --dry-run

# After verifying, perform the replacement
wp search-replace 'https://example.com/wp-content' 'https://cdn.example.com/wp-content'

# Configure CDN plugin settings
wp option update cdn_url 'https://cdn.example.com'
wp option update cdn_enabled 1

8. Lazy Loading Implementation

Enable lazy loading for images and iframes to improve initial page load times.

# WordPress native lazy loading (5.5+)
wp option update wp_lazy_loading_enabled 1

# For older versions, use plugin
wp plugin install lazy-load --activate

# Configure lazy loading settings
wp option update lazy_load_images 1
wp option update lazy_load_iframes 1

9. Remove Unused CSS and JavaScript

Minimize loaded assets by disabling unnecessary scripts and styles.

# Identify loaded scripts on homepage
wp eval 'global $wp_scripts; print_r($wp_scripts->registered);'

# Dequeue unnecessary scripts via custom plugin
cat > wp-content/mu-plugins/performance-tweaks.php << 'EOF'
<?php
add_action('wp_enqueue_scripts', function() {
    // Remove jQuery migrate
    wp_deregister_script('jquery-migrate');

    // Remove emojis
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('wp_print_styles', 'print_emoji_styles');

    // Remove block library CSS if not using Gutenberg
    wp_dequeue_style('wp-block-library');
}, 100);
EOF

10. PHP Opcode Cache Configuration

Ensure opcode cache is properly configured for optimal PHP performance.

# Check if OPcache is enabled
wp eval 'var_dump(function_exists("opcache_get_status"));'

# Get OPcache statistics
wp eval 'print_r(opcache_get_status());'

# Clear OPcache when deploying code
wp eval 'opcache_reset();'

# Check PHP version and loaded extensions
wp cli info

11. Heartbeat API Optimization

The WordPress Heartbeat API can consume significant resources. Control its behavior to reduce server load.

# Disable Heartbeat API completely
cat > wp-content/mu-plugins/disable-heartbeat.php << 'EOF'
<?php
add_action('init', function() {
    wp_deregister_script('heartbeat');
}, 1);
EOF

# Or modify Heartbeat interval
cat > wp-content/mu-plugins/modify-heartbeat.php << 'EOF'
<?php
add_filter('heartbeat_settings', function($settings) {
    $settings['interval'] = 60; // 60 seconds instead of 15
    return $settings;
});
EOF

12. REST API Performance

Optimize REST API endpoints to reduce unnecessary overhead.

# Disable REST API for non-authenticated users
cat > wp-content/mu-plugins/restrict-rest-api.php << 'EOF'
<?php
add_filter('rest_authentication_errors', function($result) {
    if (!empty($result)) {
        return $result;
    }
    if (!is_user_logged_in()) {
        return new WP_Error(
            'rest_not_logged_in',
            'You are not logged in.',
            array('status' => 401)
        );
    }
    return $result;
});
EOF

13. Cron Optimization

WordPress cron can impact performance during peak traffic. Disable WP-Cron and use system cron instead.

# Disable WordPress cron
wp config set DISABLE_WP_CRON true --raw

# Add system cron job to handle WP cron
echo "*/15 * * * * wp --path=/var/www/html cron event run --due-now" | crontab -

# List scheduled cron events
wp cron event list

# Test cron execution
wp cron test

14. Asset Minification and Concatenation

Reduce HTTP requests and file sizes through minification.

# Install asset optimization plugin
wp plugin install autoptimize --activate

# Configure via CLI
wp option update autoptimize_html_optimize 1
wp option update autoptimize_js_optimize 1
wp option update autoptimize_css_optimize 1

# Clear optimization cache
wp autoptimize cache clear

15. Performance Monitoring and Benchmarking

Establish baseline metrics and monitor performance over time.

#!/bin/bash
# performance-benchmark.sh - Monitor site performance

WP_PATH="/var/www/html"
SITE_URL="https://example.com"

echo "=== WordPress Performance Benchmark ==="
echo "Date: $(date)"

# Database size
echo -e "\nDatabase Size:"
wp --path="$WP_PATH" db size --human-readable

# Autoload size
echo -e "\nAutoload Data:"
wp --path="$WP_PATH" db query "SELECT CONCAT(ROUND(SUM(LENGTH(option_value))/1024/1024,2),'MB') as autoload_size FROM wp_options WHERE autoload='yes'"

# Post counts
echo -e "\nContent Statistics:"
wp --path="$WP_PATH" post list --post_type=post --format=count --post_status=publish | xargs -I {} echo "Published Posts: {}"
wp --path="$WP_PATH" post list --post_type=page --format=count --post_status=publish | xargs -I {} echo "Published Pages: {}"

# Plugin count
echo -e "\nActive Plugins:"
wp --path="$WP_PATH" plugin list --status=active --format=count

# Theme check
echo -e "\nActive Theme:"
wp --path="$WP_PATH" theme list --status=active --field=name

# Response time test
echo -e "\nResponse Time:"
time curl -s -o /dev/null -w "Total: %{time_total}s\n" "$SITE_URL"

# Check for updates
echo -e "\nAvailable Updates:"
wp --path="$WP_PATH" core check-update
wp --path="$WP_PATH" plugin list --update=available --format=count | xargs -I {} echo "Plugins: {}"
wp --path="$WP_PATH" theme list --update=available --format=count | xargs -I {} echo "Themes: {}"

Automated Performance Optimization

Combine techniques into a comprehensive automation script:

#!/bin/bash
# performance-optimize.sh - Complete performance optimization

set -euo pipefail

WP_PATH="/var/www/html"
LOG_FILE="/var/log/wp-performance-$(date +%Y%m%d).log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "Starting performance optimization"

# Backup first
log "Creating backup"
wp --path="$WP_PATH" db export "backup-$(date +%Y%m%d-%H%M%S).sql"

# Database optimization
log "Optimizing database"
wp --path="$WP_PATH" db optimize
wp --path="$WP_PATH" transient delete --expired

# Clear caches
log "Clearing caches"
wp --path="$WP_PATH" cache flush

# Update everything
log "Checking for updates"
wp --path="$WP_PATH" core update --minor
wp --path="$WP_PATH" plugin update --all --exclude=custom-plugin
wp --path="$WP_PATH" theme update --all

# Regenerate missing thumbnails
log "Regenerating missing thumbnails"
wp --path="$WP_PATH" media regenerate --only-missing --yes

# Performance metrics
log "Collecting performance metrics"
DB_SIZE=$(wp --path="$WP_PATH" db size --human-readable --format=json | jq -r '.Size')
log "Database size: $DB_SIZE"

log "Performance optimization completed"

Leave a Reply

Your email address will not be published. Required fields are marked *