Adding a WP-CLI Command to Your Plugin, Part 1

I wanted to write some importers for CSV files, but not one that operated from the admin screens. I wanted a command that I could pipe my data into, and populate a table.

“Simple,” I thought, and then realized I needed to parse wp-config.php for the database password. While that’s not hard, it’s really bad form, especially when you can use WP-CLI to run commands within the WordPress environment.

WP-CLI commands are scripts that, when run, have the WordPress environment bootstrapped for them. That means regular WordPress features like the $wpdb global, the is_* functions, and WP classes are present. All your plugin’s or theme’s functions and classes are available as well. WP-CLI allows you to target a specific site within a network. WP-CLI provides a framework for adding documentation for your command.

WP-CLI has a guide called the Command Cookbook that explains how to make commands. This tutorial is going to simplify the explanation a lot by leaving out most of the features.

Including the Commands

In your plugin’s main PHP file, add this:

[code language=”php”]
if (class_exists(‘WP_CLI’)) {
require(‘commands.php’);
}
[/code]

The WP_CLI class is defined only when you’re running the wp command. When you execute a plugin in the admin or website, there is no WP_CLI class. If you don’t check for the existence of the class, you will get an error message in the admin.

A Command Without Logic or Docs

Here’s a minimal command that can be invoked in two ways.

[code language=”php”]
<?php // commands.php
namespace JK\DMPM;
use \WP_CLI;

WP_CLI::add_command(‘bizdir import’, ‘JK\DMPM\Import_Command’);
class Import_Command {
public function cities() {
WP_CLI::success(‘cities’);
}
public function zips() {
WP_CLI::success(‘zips’);
}
}
[/code]

We start out declaring our namespace, and then importing WP_CLI from the global namespace into ours.

We then add our command into the WP command hierarchy.

WP_CLI::add_command('bizdir import', 'JK\DMPM\Import_Command');

add_command automatically creates a bizdir command, and then an import command below that. It then adds commands that can be invoked in two ways:

wp bizdir import cities
wp bizdir import zips

Both commands are defined in a single class, Import_Command. WP-CLI will expose any public functions as commands.

Reading from the Standard Input

Let’s change that do-nothing class to one that will read from standard input.

[code language=”php”]
class Import_Command {
public function cities() {
$stdin = fgets(STDIN);
print "$stdin";
}
public function zips() {
}
}
[/code]

Now you can type wp bizdir import cities, and it will wait for your input. When you enter one line, it will print the line back to the screen.

Next time, I’ll show how to connect to the database and import the CSV files.

Next: Part 2