Manage WordPress with Awesome using wp-cli

I spoke at WordCamp Vegas 2012 on wp-cli.

It was great to see so many people excited to use the command line!

Thanks to John Hawkins and the organizing to team for a great WordCamp, and the chance to speak.

I’ll be updating this post with additional references and notes, so please let me know if you have any questions in the comments!

Slides and sample code below.




Download slides via PDF

Sample plugin code:

Note that this is a simplified version of the command, so you will likely want to change how the temporary file saving works for general purpose use.

<?php

// Let WP_CLI know we exist!
// Earlier versions of wp-cli used WP_CLI::addCommand()
WP_CLI::add_command( 'wclv', 'WCLV_Backup_Command' );

/**
 * The WCLV Backup Plugin
 *
 * @package WCLV_Backup
 * @subpackage commands/community
 * @maintainer Mike Schroder
 */
class WCLV_Backup_Command extends WP_CLI_Command {

	/**
	 * Backup your WordPress install.
	 *
	 * @param array $args
	 * @param array $assoc_args
	 */
	function backup( $args, $assoc_args ) {
		$filename = $dbname = null;

		// If a filename isn't specified, default to "Site's Title.tar.gz".
		if ( empty( $args ) )
			$filename = '../' . escapeshellarg( get_bloginfo() ) . '.tar.gz';
		else
			$filename = $args[0];

		// If --no-db is specified, don't include the database in backup
		if ( ! isset( $assoc_args['no-db'] ) ) {
			$dbname = '../database_temp.sql';

			// This is cheating a bit, since wp-cli doesn't currently support
			// running commands within commands without re-launching itself.
			WP_CLI::run_command( array( 'db', 'export', $dbname ), array() );
		}

		// GZ/Tar and Backup the install!
		WP_CLI::line( "Backing up to '$filename' ..." );
		$result = WP_CLI::launch( "tar -zcvf $filename . $dbname", false );

		// If we created a database backup, remove the temp file.
		if ( $dbname && ! unlink( $dbname ) )
			WP_CLI::warning( "Couldn't remove temporary database backup, '$dbname'." );

		// Will automatically exit on WP_CLI::error, but not WP_CLI::success.
		if ( 0 == $result ) {
			WP_CLI::success( "Backup Complete." );
		} else {
			WP_CLI::error( "Backup Failed." );
		}
	}

	/**
	 * Output syntax for command
	 */
	public static function help() {
		WP_CLI::line( "usage: wp wclv backup [--no-db] [path/to/file]" );
	}
}

Notes:

I had a few questions on specific code for adding a command to a plugin.
This is fortunately super easy.

Create your wp-cli command just as you would per the slides, then use the following code to only add your command when the plugin is getting loaded via wp-cli (initial code courtesy of Mika’s DreamObjects plugin).

if ( defined('WP_CLI') && WP_CLI ) {
	include( PLUGIN_DIR . '/lib/wp-cli.php' );
}

2 thoughts on “Manage WordPress with Awesome using wp-cli

  1. Pingback: Ben Lobaugh Online » Recap of 2012 Las Vegas WordCamp

  2. Pingback: WordCamp Vegas 2012 Resources « wptvmods

Leave a Reply