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

This is the third in a series about writing WP-CLI commands. The previous article explained how to import CSV files into a database table. In this, we describe how to add documentation.

The best feature of the WP-CLI commands is that they come with documentation. They follow in the Unix tradition of man pages, where each command is explained in detail.

The code presented thus far has lacked documentation, so we’ll add some. The documentation is added with PHPDoc comment blocks. It’s explained well in the WP-CLI cookbook.

In the tradition of the last two posts in this series, this is a lean example, without any of the nice features. Look for the green comments.

<?php

namespace JK\DMPM;
use \WP_CLI;

/**
 * Imports CSV files into our application's tables.
 */
class Import_Command {

    /**
     * Imports a CSV file from the USGS into 
     */
    public function cities() {
        global $wpdb;
        $tablename = $wpdb->prefix.'dmpm_city';

        fgetcsv(STDIN, 1024);
        while ($fields = fgetcsv(STDIN, 1024, '|')) {
            $data = array();
            $data['id'] = $fields[0];
            $data['title'] = $fields[1];
            $data['lat'] = $fields[12];
            $data['lon'] = $fields[13];
            if ($data['title']) {
                $wpdb->insert($tablename, $data);
            }
        }
    }

    /**
     * Imports a CSV file from the federalgovernmentzipcodes.us.
     */
    public function zips() {
        global $wpdb;
        $tablename = $wpdb->prefix.'dmpm_zip';

        fgetcsv(STDIN, 1024);
        while ($fields = fgetcsv(STDIN, 1024)) {
            $data = array();
            $data['id'] = $fields[0];
            $data['city'] = $fields[2];
            $data['lat'] = $fields[5];
            $data['lon'] = $fields[6];
            $wpdb->insert($tablename, $data);
        }
    }
}
WP_CLI::add_command('bizdir import', 'JK\DMPM\Import_Command');

That’s only nine lines of comments. Now, here’s the magic part, when you type:

wp help bizdir import

You will see this:

  wp bizdir import

DESCRIPTION

  Imports CSV files into our application's tables.

SYNOPSIS

  wp bizdir import 

SUBCOMMANDS

  cities      Imports a CSV file from the USGS into 
  zips        Imports a CSV file from the federalgovernmentzipcodes.us.

You get so much benefit for so little work.

One thought on “Adding a WP-CLI Command to Your Plugin, Part 3”

Leave a Reply