Hooks conceptually are very similar to WordPress actions. WP-CLI hooks
are typically called before WordPress is loaded.
WP-CLI hooks include:
* before_invoke: - Just before a command is invoked.
* after_invoke: - Just after a command is involved.
* 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.
WP-CLI commands can create their own hooks with WP_CLI::do_hook().
# wp network meta confirms command is executing in multisite context.
WP_CLI::add_command( 'network meta', 'Network_Meta_Command', array(
'before_invoke' => function () {
if ( !is_multisite() ) {
WP_CLI::error( 'This is not a multisite install.' );
}
}
) );
<?php /** * Use WP-API at the command line. */ require_once __DIR__ . '/inc/RestCommand.php'; require_once __DIR__ . '/inc/Runner.php'; if (class_exists('WP_CLI')) { \WP_REST_CLI\Runner::load_remote_commands(); WP_CLI::add_hook('after_wp_load', '\\WP_REST_CLI\\Runner::after_wp_load'); }
/** * Sets up and hooks WP CLI to our CLI code. */ private function hooks() { WP_CLI::add_hook('after_wp_load', 'WC_CLI_Runner::after_wp_load'); WP_CLI::add_hook('after_wp_load', 'WC_CLI_Tool_Command::register_commands'); WP_CLI::add_hook('after_wp_load', 'WC_CLI_Update_Command::register_commands'); }
WP_CLI::add_hook('after_wp_load', function () { global $current_site; // Only modify `site create` command. if (implode(' ', WP_CLI::get_runner()->arguments) !== 'site create') { return; } // Subdomains are required. if (!is_subdomain_install()) { WP_CLI::error('Hercules requires subdomains mode'); } // Support `domain` arg even if `wp site create` don't. if (isset(WP_CLI::get_runner()->assoc_args['domain'])) { $domain = WP_CLI::get_runner()->assoc_args['domain']; unset(WP_CLI::get_runner()->assoc_args['domain']); } else { $domain = WP_CLI::get_runner()->assoc_args['slug']; } // Not a valid host. if (parse_url('http://' . $domain, PHP_URL_HOST) !== $domain) { WP_CLI::error('Hercules requires a valid top domain, e.g example.com'); } // Remove `www.` from the domain if any. $domain = preg_replace('|^www\\.|', '', $domain); // Split the domain. $domain = explode('.', $domain); // Can only work with two parts. if (count($domain) !== 2) { WP_CLI::error('Hercules requires a valid top domain, e.g example.com'); } // Set new slug in WP CLI. WP_CLI::get_runner()->assoc_args['slug'] = $domain[0]; // Set current site domain. $current_site->domain = $domain[1]; });