Custom WP-CLI commands for a plugin’s maintenance tasks
Every plugin with real data sooner or later needs tasks that do not belong in the admin: re-sync 20,000 products with an API, rebuild a lookup table, clean up after a failed import. A shell script that chains wp eval calls is fragile. A WP-CLI command of the plugin’s own runs with WordPress loaded, has documented arguments, a progress bar and proper exit codes, and can be called from cron and CI.
Problem: A plugin’s “resync all products” button in the admin runs into the PHP time limit after 3,000 products. The developers work around it with a wp eval-file script that nobody else knows how to call.
Solution: Register a command class with WP_CLI::add_command() only when WP-CLI is running, describe arguments in the docblock so wp help shows them, process items in batches with a progress bar, support --dry-run, and report the result with WP_CLI::success() or WP_CLI::error(), which sets the exit code.
Register the command
if ( defined( 'WP_CLI' ) && WP_CLI ) {
require_once __DIR__ . '/includes/class-ha-cli.php';
WP_CLI::add_command( 'ha', 'Ha_CLI' );
}
The class file is loaded only in WP-CLI, so normal page views do not pay for it. Every public method of the class becomes a subcommand: wp ha sync, wp ha cleanup.
A command with arguments, batches and a progress bar
class Ha_CLI {
/**
* Sync products with the supplier API.
*
* ## OPTIONS
*
* [--batch=<number>]
* : Products per batch.
* ---
* default: 100
* ---
*
* [--since=<date>]
* : Only products modified after this date (Y-m-d).
*
* [--dry-run]
* : Show what would change, write nothing.
*
* ## EXAMPLES
*
* wp ha sync --since=2025-06-01 --dry-run
*
* @when after_wp_load
*/
public function sync( array $args, array $assoc_args ): void {
$batch = max( 1, (int) $assoc_args['batch'] );
$dry_run = \WP_CLI\Utils\get_flag_value( $assoc_args, 'dry-run', false );
$query = array( 'limit' => -1, 'return' => 'ids', 'status' => 'publish' );
if ( ! empty( $assoc_args['since'] ) ) {
$query['date_modified'] = '>' . $assoc_args['since'];
}
$ids = wc_get_products( $query );
if ( ! $ids ) {
WP_CLI::success( 'Nothing to sync.' );
return;
}
$progress = \WP_CLI\Utils\make_progress_bar( 'Syncing', count( $ids ) );
$changed = 0;
$errors = 0;
foreach ( array_chunk( $ids, $batch ) as $chunk ) {
foreach ( $chunk as $id ) {
$result = ha_sync_product( $id, $dry_run );
if ( is_wp_error( $result ) ) {
WP_CLI::warning( "#{$id}: " . $result->get_error_message() );
$errors++;
} elseif ( $result ) {
$changed++;
}
$progress->tick();
}
wp_cache_flush_runtime(); // free the in-memory object cache between batches
}
$progress->finish();
$message = sprintf( '%d products %s, %d errors.', $changed, $dry_run ? 'would change' : 'changed', $errors );
$errors ? WP_CLI::error( $message ) : WP_CLI::success( $message );
}
}
The docblock is not decoration: WP-CLI parses the ## OPTIONS section to validate arguments, apply defaults and generate wp help ha sync. Positional arguments arrive in $args, named ones in $assoc_args.
wp_cache_flush_runtime() (WordPress 6.0+) empties the non-persistent object cache. In a long loop, WordPress keeps every loaded post and meta row in memory; without clearing it, the process grows until it hits the memory limit. WP_CLI::error() stops with exit code 1, so a cron job or CI step sees the failure.
Ask before destructive actions
class Ha_CLI {
// ... sync() as above
public function cleanup( array $args, array $assoc_args ): void {
global $wpdb;
$table = $wpdb->prefix . 'ha_sync_log';
$count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE created_at < NOW() - INTERVAL 90 DAY" );
WP_CLI::confirm( "Delete {$count} log rows older than 90 days?", $assoc_args );
$wpdb->query( "DELETE FROM {$table} WHERE created_at < NOW() - INTERVAL 90 DAY" );
WP_CLI::success( "Deleted {$count} rows." );
}
}
WP_CLI::confirm() asks interactively and is skipped with --yes, which is what scripts pass.
Use it
wp help ha sync wp ha sync --since=2025-06-01 --dry-run wp ha sync --batch=200 wp ha cleanup --yes
From cron: cd /var/www/example.com/public && wp ha sync --quiet. The built-in commands that every developer should know: essential WP-CLI commands.
NOTE: WP-CLI runs as the shell user. Run it as the same user as PHP-FPM (sudo -u www-data wp ...), or files it creates (cache, uploads, logs) belong to the wrong user and the website cannot write to them later.