WP_CLI::add_hook()public staticWP-CLI 1.0

Schedule a callback to be executed at a certain point.

Hooks conceptually are very similar to WordPress actions. WP-CLI hooks are typically called before WordPress is loaded.

WP-CLI hooks include:

  • before_add_command:<command> - Before the command is added.
  • after_add_command:<command> - After the command was added.
  • before_invoke:<command> (1) - Just before a command is invoked.
  • after_invoke:<command> (1) - Just after a command is invoked.
  • find_command_to_run_pre - Just before WP-CLI finds the command to run.
  • before_registering_contexts (1) - Before the contexts are registered.
  • before_wp_load - Just before the WP load process begins.
  • before_wp_config_load - After wp-config.php has been located.
  • after_wp_config_load - After wp-config.php has been loaded into scope.
  • after_wp_load - Just after the WP load process has completed.
  • before_run_command (3) - Just before the command is executed.

The parentheses behind the hook name denote the number of arguments being passed into the hook. For such hooks, the callback should return the first argument again, making them work like a WP filter.

WP-CLI commands can create their own hooks with WP_CLI::do_hook().

If additional arguments are passed through the WP_CLI::do_hook() call, these will be passed on to the callback provided by WP_CLI::add_hook().

# `wp network meta` confirms command is executing in multisite context.
WP_CLI::add_command( 'network meta', 'Network_Meta_Command', array(
   'before_invoke' => function ( $name ) {
	   if ( !is_multisite() ) {
		   WP_CLI::error( 'This is not a multisite installation.' );
) );

Method of the class: WP_CLI{}

No Hooks.


null. Nothing (null).


$result = WP_CLI::add_hook( $when, $callback );
$when(string) (required)
Identifier for the hook.
$callback(mixed) (required)
Callback to execute when hook is called.

WP_CLI::add_hook() code WP-CLI 2.8.0-alpha

public static function add_hook( $when, $callback ) {
	if ( array_key_exists( $when, self::$hooks_passed ) ) {
				'Immediately invoking on passed hook "%s": %s',
				Utils\describe_callable( $callback )
		call_user_func_array( $callback, (array) self::$hooks_passed[ $when ] );

	self::$hooks[ $when ][] = $callback;