WordPress Development

Writing Custom WP-CLI Commands for Your Plugins and Sites

Writing Custom WP-CLI Commands for Your Plugins and Sites

Some of the most useful code I write for client sites never appears on the front end. It’s custom WP-CLI commands: tools for importing data from another system, cleaning up thousands of products, regenerating calculated fields, syncing with external APIs or running site-specific maintenance tasks.

WP-CLI’s built-in commands cover a lot, but every site has its own needs. Writing custom commands gives you reliable, repeatable tools that run without browser timeouts, can be scheduled with cron and can be used safely by anyone on the team.

Here’s how to write custom WP-CLI commands well.

Why custom commands are worth it

Compared with running one-off scripts or admin page buttons, custom WP-CLI commands:

  • Avoid browser timeouts, because they run in the terminal, not through the web server.
  • Can process large datasets in batches with progress feedback.
  • Are repeatable and documented, so other developers know how to run them.
  • Can be automated with cron or deployment scripts.
  • Run with full WordPress context, so all your functions, hooks and plugins are available.
  • Are safer, with dry-run modes and confirmations for destructive operations.

Registering a simple command

Commands are registered with WP_CLI::add_command, but only when WP-CLI is running. Put command code in your plugin:

Run it with:

The first argument to the callback holds positional arguments, and the second holds named options, like –dry-run or –limit=100.

Using a class for multiple subcommands

For anything beyond trivial commands, use a class. Each public method becomes a subcommand:

Now you can run:

Document with docblocks

WP-CLI reads the docblock above each command to build help text and validate arguments. The OPTIONS section defines:

  • Positional arguments, like <file>.
  • Named options, like [–limit=<number>], with optional defaults.
  • Flags, like [–dry-run].
  • Allowed values, using an options list in the YAML-like block.

WP-CLI validates input against this documentation before your code runs, so missing required arguments produce helpful errors. Good documentation also means teammates can run wp help to understand the command without reading the code.

Output and feedback

WP-CLI provides functions for consistent output:

  • WP_CLI::log() for general messages.
  • WP_CLI::success() for successful completion.
  • WP_CLI::warning() for problems that don’t stop the command.
  • WP_CLI::error() for fatal problems; it exits the command with an error status.
  • WP_CLI::debug() for messages shown only with the –debug flag.

Formatted output

For lists of data, use WP_CLIUtilsformat_items, which supports table, JSON, CSV, YAML and count formats, like built-in commands:

Supporting a –format option makes your command useful in scripts and pipelines.

Progress bars

For long operations, progress bars reassure the person running the command that something is happening and show how long is left.

Safety for destructive commands

Commands that delete or modify data should be safe by default:

  • Dry-run mode: show what would happen without changing anything. I make dry run the default for dangerous commands, requiring an explicit flag to make real changes.
  • Confirmation prompts: WP_CLI::confirm() asks the user to confirm before continuing. Allow a –yes flag to skip confirmation in automated scripts.
  • Backups: for major operations, remind users to back up, or run a database export first.
  • Clear output: report exactly what changed.

Processing large datasets

For thousands of items, process in batches to keep memory use under control:

Clearing the in-memory object cache between batches prevents memory from growing throughout long runs. If wp_cache_flush_runtime isn’t available in your environment, other approaches exist, like resetting the cache’s internal arrays, depending on your object cache.

Be careful when your processing changes which posts match the query; paging through a result set that shrinks as you process it can skip items. Querying by ID ranges or processing until no matching items remain avoids that problem.

Error handling and exit codes

Commands should exit with a non-zero status when they fail, so scripts and cron jobs can detect failures. WP_CLI::error() does this automatically. For partial failures, collect errors, report them at the end and decide whether to exit with an error.

Catch exceptions from external API calls or file operations, log useful messages and continue processing other items where it makes sense.

Running commands on a schedule

Custom commands work well with system cron:

The –quiet flag suppresses informational output, while errors are still reported. Combine with heartbeat monitoring to know if scheduled commands stop running.

Distributing commands

You can include commands in:

  • A site-specific plugin or must-use plugin, for commands specific to one site.
  • Your public plugin, offering CLI commands to all users. Many popular plugins do this.
  • A standalone WP-CLI package, for commands that work across many sites independent of any plugin.

Testing commands

  • Test on staging with realistic data.
  • Use dry-run mode first.
  • Test with edge cases: no matching items, invalid arguments and API failures.
  • Check memory usage on large datasets.

Commands I build for most client sites

Over time, I’ve found myself writing similar commands for many projects. A few that pay for themselves quickly:

  • An import command that reads products, posts or users from a CSV file supplied by the client, validates every row, reports problems clearly and supports a dry run. Imports through admin screens time out on large files; a command handles thousands of rows reliably.
  • A cleanup command that removes expired data, like old logs, abandoned carts or outdated records, according to the site’s retention rules. Scheduled nightly, it keeps the database lean.
  • A sync command that pulls data from an external system, like inventory levels or exchange rates, with retries and clear error reporting. Running it from cron is far more reliable than relying on visitor traffic.
  • An audit command that checks site-specific rules, like every product having a price and an image, or every service page having a booking link, and lists exceptions. Editors appreciate a quick report of what needs attention.
  • A data repair command for fixing problems after migrations or bugs, like recalculating totals or regenerating derived fields.

Each command is small, but together they turn recurring chores into reliable routines.

Make commands discoverable

Group related commands under a single namespace, like wp mysite, so the team can run wp help mysite to see everything available. Write help text as if for someone who has never seen the code. A command nobody knows about doesn’t save anyone time.

Logging for scheduled commands

When commands run unattended, write meaningful log output to a file, including start and end times, counts processed and any warnings. If a sync fails at three in the morning, the log should explain why without anyone needing to reproduce the problem.

Keep commands safe for others

Assume someone else will run your command one day, perhaps in a hurry. Defaults should be safe, destructive actions should require explicit flags and output should make it obvious what happened. A command that can wipe data with a single typo is a liability; a command that asks for confirmation and shows a dry run first is a tool people trust.

Testing commands safely

Run new commands against a staging copy first, with realistic data. Check the dry-run output carefully, then run for real and compare the results with what you expected. For commands that touch many records, test on a small subset first using a limit option. That way, any mistakes affect a handful of items rather than the whole site.

Once a command proves reliable, add it to your project documentation with an example of how and when to run it. Over time, these documented commands become a toolkit that anyone on the team can use with confidence.

Version your commands

When a command’s behaviour changes, note it in your plugin’s changelog. Scripts and cron jobs that depend on specific options or output formats can break silently if a command changes without warning, so treat command interfaces like any other public API and change them carefully.

Frequently asked questions

Do custom WP-CLI commands load my plugins?

Yes. WP-CLI loads WordPress fully, including active plugins and the theme, unless you use flags like –skip-plugins.

Where should I put custom command code?

In a plugin, loaded only when WP-CLI is running. Avoid putting it in a theme.

How do I add arguments to my command?

Define them in the docblock’s OPTIONS section. WP-CLI parses and validates them and passes them to your method.

Can I call other WP-CLI commands from my command?

Yes, with WP_CLI::runcommand(), which can run commands and capture their output.

Final thoughts

Custom WP-CLI commands turn repetitive and risky tasks into dependable tools. Use classes for related subcommands, document arguments in docblocks, give clear feedback with progress bars and formatted output, make destructive commands safe with dry runs and confirmations, process large datasets in batches and return proper exit codes for automation. Once you start writing them, you’ll find more and more admin chores that deserve a command of their own.