REST API & Developer PHP Intermediate

Add a Custom WP-CLI Command

Create your own wp command, like wp nahnu cleanup, to run site maintenance tasks from the terminal.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 40 lines
if ( defined( 'WP_CLI' ) && WP_CLI ) {
	/**
	 * Clean up expired transients and old auto-drafts.
	 *
	 * ## OPTIONS
	 *
	 * [--dry-run]
	 * : Show what would be deleted without deleting anything.
	 *
	 * ## EXAMPLES
	 *
	 *     wp nahnu cleanup
	 *     wp nahnu cleanup --dry-run
	 */
	WP_CLI::add_command( 'nahnu cleanup', function ( array $args, array $assoc_args ): void {
		$dry_run = (bool) WP_CLI\Utils\get_flag_value( $assoc_args, 'dry-run', false );

		$drafts = get_posts( [
			'post_status'    => 'auto-draft',
			'post_type'      => 'any',
			'date_query'     => [ [ 'before' => '7 days ago' ] ],
			'fields'         => 'ids',
			'posts_per_page' => -1,
		] );

		WP_CLI::log( sprintf( 'Old auto-drafts: %d', count( $drafts ) ) );

		if ( $dry_run ) {
			WP_CLI::success( 'Dry run: nothing deleted.' );
			return;
		}

		foreach ( $drafts as $id ) {
			wp_delete_post( $id, true );
		}
		delete_expired_transients( true );

		WP_CLI::success( 'Cleanup complete.' );
	} );
}

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

WP-CLI is the fastest way to run maintenance on a WordPress site, and it’s easy to add your own commands. They run with WordPress fully loaded, so you can use any WordPress function.

How it works

The code only runs when WordPress is loaded by WP-CLI, which defines the WP_CLI constant. WP_CLI::add_command() registers the command name and the function to run.

The comment block above it becomes the command’s help text, shown by wp help nahnu cleanup. The [--dry-run] option there is read with get_flag_value().

WP_CLI::log() prints output and WP_CLI::success() prints a green success message.

Things to watch

  • For bigger commands, register a class instead of a function. Each public method becomes a subcommand.
  • Commands can be run from cron jobs on the server, for example wp nahnu cleanup --path=/var/www/site.

How to test it

In a terminal, in your site folder, run wp nahnu cleanup --dry-run. You should see the count of old auto-drafts and a success message.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only