One way to work with existing WP-CLI commands is through the WP_CLI::runcommand()
.
Here are two examples how we can filter an existing WP-CLI command, namely the wp user list
command based on WP_User_Query
and it’s pre_user_query
hook:
Run a custom script in WP-CLI
Let’s write our script.php
file with:
<?php
add_action( 'pre_user_query', 'wpse_pre_user_query' );
WP_CLI::runcommand(
'user list --role=customer --orderby=ID --order=asc',
[ 'launch' => false ]
);
remove_action( 'pre_user_query', 'wpse_pre_user_query' );
/**
* Modify WP_User_Query WHERE part.
*/
function wpse_pre_user_query( $user_query ) {
global $wpdb;
$user_query->query_where .= " AND {$wpdb->users}.ID > 200 ";
}
where we run the command in the current process with 'launch' => false
to make the current filtering possible. Here we use the pre_user_query
as explained in the answer by Pete Nilson.
We could also have grabbed the parsed json output from the command to work with it if needed:
$json = WP_CLI::runcommand(
'user list --role=customer --orderby=ID --order=asc',
[ 'launch' => false, 'parse' => 'json', 'return' => true ]
);
Then we can run it from the command-line with:
wp eval-file script.php
Run a custom command in WP-CLI
Another approach would be to write a custom command with WP_CLI::add_command()
to support:
wp user wpse_list_query --gt_user_id=200
where the command part is user wpse_list_query
with the --gt_user_id
argument to only fetch users with a user ID that is greater than a given value.
Here’s a plugin skeleton for that:
if ( defined( 'WP_CLI' ) && WP_CLI ) {
/**
* Custom User List Query Command.
*
* [--gt_user_id=<user_id>]
* : Greater than a given user ID.
*
* @when before_wp_load
*/
$wpse_command_callback = function( $args, $assoc_args ) {
if ( isset ( $assoc_args['gt_user_id'] ) ) {
$uid = $assoc_args['gt_user_id'];
WP_CLI::add_wp_hook(
'pre_user_query',
function ( $user_query ) use ( $uid ) {
global $wpdb;
$user_query->query_where .= $wpdb->prepare(
" AND {$wpdb->users}.ID > %d",
$uid
);
},
$priority = 10,
$accepted_args = 1
);
}
WP_CLI::runcommand(
'user list --role=customer --orderby=ID --order=asc',
[ 'launch' => false ]
);
};
WP_CLI::add_command( 'user wpse_list_query', $wpse_command_callback );
}
Note the PHPDoc is used to define the optional parameters and when to run this. If we skip the brackets in:
* [--gt_user_id=<user_id>]
then the argument is no longer optional.
Hope you can adjust this further to your needs!