Executing WP CLI commands inside WP CLI command with WP_CLI::runcommand()

Post Reads 145 reads

In this article let’s learn about how to execute another WP CLI commands.

Note: If you read some recent articles then you can skip some below steps that are related to plugin creation.

Create Empty Plugin Create Empty Plugin

  • Create a new folder wordpress-examples into plugins directory /wp-content/plugins/
  • Create a file wordpress-examples.php and add the below code into it.
<?php
 /**
 Plugin Name: WordPress Examples
 */ 

Note: If you want to add some additional information then you can get it from gist snippet – WordPress Complete Plugin Readme File.

Now you can see our WordPress Examples plugin exists into the plugins list.

Now, Activate the WordPress Examples plugin.

Register WP CLI Command Register WP CLI Command

Register PHP class WordPress_Examples_WP_CLI e.g.

if ( ! class_exists( 'WordPress_Examples_WP_CLI' ) && class_exists( 'WP_CLI_Command' ) ) :
       class WordPress_Examples_WP_CLI extends WP_CLI_Command {

       }
endif;

Here,

We have registered a new class WordPress_Examples_WP_CLI and extend it with WP_CLI_Command.

Add Examples Command Add Examples Command

Now let’s register the examples. E.g.

       WP_CLI::add_command( 'examples', 'WordPress_Examples_WP_CLI' ); 

Here,

We have used the function WP_CLI::add_command() to register our examples command.

The function WP_CLI::add_command() accepts 2 parameters. The first parameter is the command name. Which is examples in our case.

And second is a callback class which is WordPress_Examples_WP_CLI.

Add execute_commands sub command Add execute_commands sub command

         public function execute_commands( $args, $assoc_args ) {
           WP_CLI::line( 'Hello' );
         }

Here,

We have added a function execute_commands() with two parameters.

  • $args contain the arguments.
  • $assoc_args contain the associate arguments.

Testing the Command Testing the Command

Open command prompt/terminal. Go to your WordPress setup. I have set up WordPress in D:\xampp\htdocs\dev.test

So, Execute the below commands:

  • cd D:\xampp\htdocs\dev.test
  • wp examples execute_commands

You can see the output something like below:

 λ wp examples execute_commands
 Hello

This command just shows the string Hello.

Using WP_CLI::runcommand() Using WP_CLI::runcommand()

Its time to execute another command in our WP CLI command with WP_CLI::runcommand().

public function execute_commands( $args, $assoc_args ) {
	WP_CLI::runcommand( 'cli info' );
}

Let’s execute the command wp examples execute_commands.

λ wp examples execute_commands
 OS:     Windows NT 6.1 build 7601 (Windows 7 Ultimate Edition Service Pack 1) i586
 Shell:  C:\Windows\system32\cmd.exe
 PHP binary:     D:\xampp\php\php.exe
 PHP version:    7.0.8
 php.ini used:   D:\xampp\php\php.ini
 WP-CLI root dir:        phar://wp-cli.phar/vendor/wp-cli/wp-cli
 WP-CLI vendor dir:      phar://wp-cli.phar/vendor
 WP_CLI phar path:       D:\xampp\htdocs\dev.test
 WP-CLI packages dir:    C:\Users\intel/.wp-cli/packages/
 WP-CLI global config:
 WP-CLI project config:
 WP-CLI version: 2.4.0
 D:\xampp\htdocs\dev.test

Here, we see the result of the WP CLI command wp cli info.

Note: When we use the function WP_CLI::runcommand() then we don’t need to pass the prefix wp. So, wp cli info should be cli info.

Experiment with Examples Experiment with Examples

Example 1

public function execute_commands( $args, $assoc_args ) {

	// Execute `wp cli info` CLI command.
	WP_CLI::runcommand( 'cli info' );

	// Execute `wp plugin list --status=active` CLI command.
	WP_CLI::runcommand( 'plugin list --status=active' );

}

Lets execute command wp examples execute_commands.

λ wp examples execute_commands
 OS:     Windows NT 6.1 build 7601 (Windows 7 Ultimate Edition Service Pack 1) i586
 Shell:  C:\Windows\system32\cmd.exe
 PHP binary:     D:\xampp\php\php.exe
 PHP version:    7.0.8
 php.ini used:   D:\xampp\php\php.ini
 WP-CLI root dir:        phar://wp-cli.phar/vendor/wp-cli/wp-cli
 WP-CLI vendor dir:      phar://wp-cli.phar/vendor
 WP_CLI phar path:       D:\xampp\htdocs\dev.test
 WP-CLI packages dir:    C:\Users\intel/.wp-cli/packages/
 WP-CLI global config:
 WP-CLI project config:
 WP-CLI version: 2.4.0
 +--------------------+--------+--------+---------+
 | name               | status | update | version |
 +--------------------+--------+--------+---------+
 | wordpress-examples | active | none   |         |
 +--------------------+--------+--------+---------+

Here, we have executed two commands.

  • wp cli info – It displays the WP CLI information.
  • wp plugin list --status=active – It displays active plugins.

Example 2

public function execute_commands( $args, $assoc_args ) {

	WP_CLI::runcommand( 'plugin list --format=json --status=active' );

}
λ wp examples execute_commands
 [{"name":"wordpress-examples","status":"active","update":"none","version":""}]

Example 3

Lets, Get the result of the command in a variable to perform some operations like:

public function execute_commands( $args, $assoc_args ) {

	$options = array(
	  'return'     => true,   // Return 'STDOUT'; use 'all' for full object.
	  'parse'      => 'json', // Parse captured STDOUT to JSON array.
	  'launch'     => false,  // Reuse the current process.
	  'exit_error' => true,   // Halt script execution on error.
	);
	$plugins = WP_CLI::runcommand( 'plugin list --format=json --status=active', $options );

	foreach ($plugins as $key => $plugin) {
		WP_CLI::line( $plugin['name'] . ' status is ' . $plugin['status'] );
	}

}
λ wp examples execute_commands
 wordpress-examples status is active

Here, In function WP_CLI::runcommand() we have passed 2 arguments.

  • First is plugin list --format=json --status=active which is the WP CLI command.
  • And second is the $options which is the array of configuration values.

Example 4

public function execute_commands( $args, $assoc_args ) {

	$options = array(
	  'return'     => true,   // Return 'STDOUT'; use 'all' for full object.
	  'parse'      => 'json', // Parse captured STDOUT to JSON array.
	  'launch'     => false,  // Reuse the current process.
	  'exit_error' => true,   // Halt script execution on error.
	);
	$posts = WP_CLI::runcommand( 'post list --format=json', $options );

	foreach ($posts as $key => $post) {
		WP_CLI::line( $post['ID'] . ' | ' . $post['post_title'] );
	}

}
λ wp examples execute_commands
 162 | Sample Post
 160 | Sample Post
 89 | Another Post
 1 | Hello world!

Oh! Don’t forget that we learned about the class \WP_CLI\Formatter(). It displays the well-formatted data.

Let’s try to implement it in the above example.

public function execute_commands( $args, $assoc_args ) {

	$options = array(
	  'return'     => true,   // Return 'STDOUT'; use 'all' for full object.
	  'parse'      => 'json', // Parse captured STDOUT to JSON array.
	  'launch'     => false,  // Reuse the current process.
	  'exit_error' => true,   // Halt script execution on error.
	);
	$posts = WP_CLI::runcommand( 'post list --format=json', $options );

	$display_fields = array(
		'ID',
		'post_title',
	);
	$formatter      = new \WP_CLI\Formatter( $assoc_args, $display_fields );
	$formatter->display_items( $posts );

}

Now, Execute wp examples execute_commands.

λ wp examples execute_commands
 +-----+--------------+
 | ID  | post_title   |
 +-----+--------------+
 | 162 | Sample Post  |
 | 160 | Sample Post  |
 | 89  | Another Post |
 | 1   | Hello world! |
 +-----+--------------+

We can see the data in the table format. To demonstrate the WP_CLI::runcommand() I have used posts example.

You can use the command wp post list to list the posts. E.g.

λ wp post list                                                            
 +-----+--------------+---------------+---------------------+-------------+
 | ID  | post_title   | post_name     | post_date           | post_status |
 +-----+--------------+---------------+---------------------+-------------+
 | 162 | Sample Post  | sample-post-2 | 2019-11-05 02:11:16 | publish     |
 | 160 | Sample Post  | sample-post   | 2019-11-05 02:10:05 | publish     |
 | 89  | Another Post | another-post  | 2019-10-15 23:32:57 | publish     |
 | 1   | Hello world! | hello-world   | 2019-10-05 08:23:44 | publish     |
 +-----+--------------+---------------+---------------------+-------------+

Executing WP CLI commands inside WP CLI command with WP_CLI::runcommand().

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top
%d bloggers like this: