Creating a WP CLI Command

Creating your own commands for WP CLI is very simple. There are several options to do this, and below we will consider some of them.

Methods for formatting output in the console, see here.

Custom commands trigger after the hook wp_loaded.

Custom commands are executed after the entire WordPress environment is loaded. First, the full WP loading occurs - wp-config.php is loaded (from which wp-settings.php is cut), and then the actual file wp-settings.php is loaded. For versions below WP 4.6, instead of wp-settings.php, a custom rewritten version for WP-CLI is loaded: wp-cli\php\wp-settings-cli.php.

Then the Admin part of WP is loaded - the file wp-admin/includes/admin.php.

And only after that, the command is executed.

For more details, see the methods:

There are exceptions (commands that run earlier among WP), for example, the command wp cli info.

Option 1: Creating a Single WP CLI Command via PHP Function

Use the method WP_CLI::add_command()

WP_CLI::add_command( 'my command', function ( $args, $assoc_args ) {

	WP_CLI::success( $args[0] . ' ' . $assoc_args['append'] . ' ' . $assoc_args['all'] );
} );

Now use it in the command line:

$ wp my command arg1 --append=foo --all

Success: arg1 foo 1

Option 2: Creating Commands via Class

  1. Create a file class-My_Command.php the file name can of course be specified by you.

  2. Include the file in PHP, for example, in the theme's functions.php or in a plugin.

  3. Add the following code to the file:
<?php

if( ! defined( 'WP_CLI' ) ){
	return;
}

WP_CLI::add_command( 'mycommand', My_Command::class, [] );

class My_Command extends WP_CLI_Command {

	public function __construct(){}

	/**
	 * Working with cache and removable data (post meta).
	 *
	 * ## OPTIONS
	 *
	 * <rm>
	 * : Removes cache.
	 *
	 * [--stubs]
	 * : Remove only stubs from cache. The same as not specify any params.
	 *
	 * [--meta]
	 * : Remove past meta associated with this plugin.
	 *
	 * ## EXAMPLES
	 *
	 *     wp mycommand cache rm           # treats as `rm --stubs`
	 *     wp mycommand cache rm --meta
	 *
	 * @param $args
	 * @param $params
	 */
	public function cache( $args, $params ){

		// clear cache
		if( 'rm' === array_shift( $args ) ){

			$type = 'rm_stub_thumbs';
			isset( $params['thumbs'] ) && $type = 'rm_thumbs';

			FooClass::init()->force_clear( $type );
		}
	}

	/**
	 * Some custom code (for tests for example).
	 *
	 * ## EXAMPLES
	 *
	 *     wp mycommand custom
	 */
	public function custom(){

		// clear cache
		if( 'rm' === reset( $args ) ){

			$type = 'rm_stub_thumbs';
			isset( $params['thumbs'] ) && $type = 'rm_thumbs';

			FooClass::init()->force_clear( $type );
		}
	}

}

Now to create another command, you just need to add a method to the created class. The method name will become the name of the first argument of the command.