Custom WP-CLI command

To develop custom WP-CLI command in plugin is handy tool if want to run a task without go to admin panel and perform a bunch of clicks to do a task. WP-CLI can save time by just type one line of commands.

Let’s jump in the WP-CLI jungle-

The challenge is, get a user’s info from API. For example: a user mrinal013 (I love to hack myself) which return a object from API endpoint and store it in options table of WordPress.

To start this challenge, assume we have wp-cli installed in system. Or, grab it from here.

At first we do the whole task in a class. For test purpose, this is CustomWPCLI . In __construct(),I hooked mrinal_cli_register_commands()with cli_init action hook. cli_init hook worth to introduction. cli_init hook initialize when WP-CLI run.

function __construct() {
    add_action( 'cli_init', array( $this, 'mrinal_cli_register_commands' ) );

However, next write the mrinal_cli_register_commands(). In this function, WP_CLI add a command by WP_CLI::add_command( command_name, callback_function ).

function mrinal_cli_register_commands() {
    WP_CLI::add_command( 'github', array( $this, 'http_request' ) );

Finally, this callback_functiondo make a GET request by using WP_CLI\Utils\http_request. Here, callback_function accept arguments array. Here, we use only one. So that, if the arguments array name is $user, than call only the first argument by $user[0]. Then at last command I update github key with response object, at WP options table.

function http_request( $user ) {
    $response = WP_CLI\Utils\http_request( 'GET', '' . $user[0] );
    update_option( 'github', $response );

Full plugin’s code is at

Leave a Reply

Your email address will not be published.