Mastering Media Optimizer with WP-CLI: The Ultimate Command-Line Guide

Media Opti 11

Welcome to the official developer guide for managing Media Optimizer via the WordPress Command-Line Interface (WP-CLI). If you are a developer, a server administrator, or manage websites for clients, using WP-CLI can dramatically accelerate your workflow, automate repetitive tasks, and give you a level of control that is impossible to achieve through a graphical user interface alone.

This comprehensive guide will walk you through every command offered by Media Optimizer, providing practical examples, advanced usage patterns, and best-practice recommendations.

Why Use WP-CLI with Media Optimizer?

While our in-plugin dashboard is designed to be intuitive and user-friendly, the command line offers unparalleled power and efficiency for several key scenarios:

  • Automation & Scripting: You can chain Media Optimizer commands with other WP-CLI commands in shell scripts to fully automate site setup, maintenance, or migration. Imagine deploying a new site and having all its images optimized automatically as part of your deployment script.
  • Performance on Large Sites: For websites with tens or hundreds of thousands of images, running a bulk optimization process via the command line is significantly more stable and reliable than through a web browser. It bypasses potential HTTP timeouts and PHP limits imposed by the web server, running directly as a server process.
  • Headless Operations: If you are managing a server without a graphical interface or need to perform maintenance tasks without logging into the WordPress admin, WP-CLI is your essential toolkit.
  • Debugging: The command line often provides more direct and verbose feedback, making it easier to diagnose issues with file permissions, server configurations, or the optimization process itself.

Prerequisites

Before you begin, please ensure the following:

  1. WP-CLI is Installed: You must have WP-CLI installed and working on your server. You can verify this by running wp –info in your WordPress root directory.
  2. Sudo/User Permissions: You should run WP-CLI commands as the user that owns the web files (often www-data or your own user account). To do this, you can use sudo -u www-data -i — wp … or simply run the commands as a user with appropriate permissions.
  3. Media Optimizer is Active: The plugin must be installed and activated for the wp media-optimizer command to be available.

The Core Command: wp media-optimizer regenerate

This is the command-line equivalent of the “Run Bulk Optimization” button. It is the primary tool for processing your entire library and other configured directories.

Basic Usage:

< > Bash


    wp media-optimizer regenerate


When you run this command, the plugin will perform the following steps:

  1. Scan: It scans all directories enabled in your settings (e.g., uploads, themes, plugins).
  2. Filter: It identifies all images that have not yet been optimized into your selected formats (WebP and/or AVIF) and that are not excluded by your settings.
  3. Process: It processes the found images in batches, sending them to the configured conversion method (either local or remote API).
  4. Report: It displays a live progress bar, showing you exactly how many images have been processed.

This is ideal for the initial optimization of a website or for catching any images that were missed.

Advanced Usage & Options

Option: –force

The –force flag is a powerful tool that tells the plugin to ignore its history and re-process every single image it finds, even those that have already been optimized.

Command:

< > Bash


    wp media-optimizer regenerate --force


When should you use –force?

  • After Changing Quality Settings: If you decide to change your “Conversion Strategy” (e.g., from 85 to 90), the existing images will not be automatically re-optimized. Running a forced regeneration will re-compress every image with the new, higher quality settings.
  • After Enabling a New Format: If you initially only used WebP and later decide to add AVIF, a forced regeneration will create the missing AVIF versions for your entire library.
  • Troubleshooting: If you suspect some images were corrupted or incorrectly processed, a forced regeneration is a surefire way to fix them.
  • After a Server Migration: When moving to a new server with better tools (e.g., a newer version of cwebp), forcing a regeneration can result in smaller file sizes for your entire library.

Warning: A forced regeneration will consume a significant number of credits if you are using the remote API, as every single image size will be re-processed. Use it deliberately.

Integrating with Shell Scripts

Here’s an example of how you can use this command in a deployment script after migrating a database and files:

< > Bash


    #!/bin/bash

# A simple deployment script
echo "Running database migrations..."
wp db upgrade

echo "Flushing rewrite rules..."
wp rewrite flush

echo "Clearing all caches..."
wp cache flush

echo "Starting Media Optimizer bulk regeneration..."
# We assume the settings are already configured for the desired formats.
wp media-optimizer regenerate

echo "Deployment complete and images are being optimized!"

Managing Settings via WP-CLI

For full automation, you need the ability to read and write plugin settings directly from the command line. Media Optimizer stores all its settings in a single entry in the wp_options table, making this straightforward with standard WP-CLI commands.

All settings are stored under the option key: mo_settings.

Viewing Current Settings

To see your entire current configuration in JSON format:

< > Bash


        wp option get mo_settings --format=json


  

This is incredibly useful for verifying that your settings were imported correctly or for checking the current configuration of a client’s site without logging in.

Modifying a Single Setting

Let’s say you want to enable the AVIF format from the command line. This requires modifying the output_formats array within the main option. We can do this with wp option patch.

Command to add AVIF:

< > Bash


    wp option patch update mo_settings output_formats avif --format=json


Command to switch to remote WebP conversion:

< > Bash


    wp option patch update mo_settings webp_conversion_method remote


This patch command is surgical. It updates only a single key within the serialized array, leaving all other settings untouched.

Exporting and Importing Settings

While our plugin offers a graphical interface for settings synchronization, you can achieve the same (and even more powerful) results with WP-CLI, which is perfect for scripting.

Exporting Settings to a File:

< > Bash


        # Get the settings and save them to a file, excluding the API key
wp option get mo_settings --format=json | jq 'del(.api_key)' > mo_settings_backup.json


Importing Settings from a File:

< > Bash


    # Read the JSON file and update the option on a new site
wp option update mo_settings "$(cat mo_settings_backup.json)" --format=json
        

  

This two-command combo allows you to create a “master” configuration file and instantly apply it to every new client site you build.

Practical Use Case: Setting Up a New Client Site

Imagine you’re a web agency. You’ve just created a new site for a client and want to configure Media Optimizer with your agency’s preferred settings and run the initial optimization.

Here’s your script: setup_client_site.sh

< > Bash


    #!/bin/bash

# Check if plugin is active
if ! $(wp plugin is-active media-optimizer); then
  echo "Media Optimizer is not active. Activating now..."
  wp plugin activate media-optimizer
fi

# Import master settings from a local file
echo "Importing master settings..."
wp option update mo_settings "$(cat /path/to/your/master_mo_settings.json)" --format=json

# Set the client's unique API key (passed as an argument to the script)
CLIENT_API_KEY=$1
if [ -z "$CLIENT_API_KEY" ]; then
  echo "Error: Please provide the client's API key as the first argument."
  exit 1
fi
echo "Setting client API key..."
wp option patch update mo_settings api_key $CLIENT_API_KEY

# Run the initial bulk optimization
echo "Starting bulk optimization. This may take a while..."
wp media-optimizer regenerate

echo "Client site is configured and optimizing!"
   

You could then run this script with a single command: ./setup_client_site.sh “client_api_key_here”.

Conclusion

Media Optimizer’s WP-CLI integration transforms it from a simple plugin into a powerful, scriptable tool for professionals. By mastering the regenerate command and leveraging wp option to manage settings, you can automate your entire image optimization workflow, ensure consistency across all your sites, and perform complex tasks with a level of speed and reliability that a graphical interface can never match. This is optimization at scale, designed for the modern web developer.