PeterJohn Hunt

Building A Custom WP-CLI Command

Check out the code from tutorial in this Github repo and leave a comment below!

1) Documentation

Also check out my WP-CLI Publish command for an example of a global WP-CLI command

2) Build an initial command

include a file for your command from functions.php or your plugin:

//≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
// ✅ Includes
//≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
/**
 * Include files
 */
if ( defined( 'WP_CLI' ) && WP_CLI ) {
    require_once 'includes/wp-cli-commands.php';
}

Base command:

class WP_CLI_Commands {
    /**
     * Test CLI
     * 
     * ## EXAMPLES
     *
     *     wp custom test
     *
     * @subcommand test
     *
     * @when after_wp_load
     */
    function test( $args, $assoc_args ) {
        WP_CLI::success( "Success!" );
    }
}
WP_CLI::add_command( 'custom', 'WP_CLI_Commands' );

Advanced comments:

* 
* ## OPTIONS
* 
* <filename>
* : The name of the file to import
* 
* [--format=<format>]
* : Output format
* ---
* default: table
* options:
*   - table
*   - csv
*   - json
* ---
*

3) WP_CLI provided utilities

Getting args

list( $filename ) = $args;
$dry_run = $assoc_args['dry-run'] ?? false;
$format  = $assoc_args['format'] ?? 'table';

Errors

if ( ! file_exists( $filename ) ) {
    WP_CLI::error( "Missing file: {$filename}" );
}

CSV iterator

$rows = new WP_CLI\Iterators\CSV($filename);
foreach ($rows as $row) {
    WP_CLI::log($row['First Name']);
}

Output Formatter

WP_CLI\Utils\format_items( $format, $rows, ['First Name', 'Last Name', 'Email'] );

4) Examples

CSV

First Name,Last Name,Email
John,Smith,john.smith@mailinator.com
Jane,Doe,jane.doe@mailinator.com