wp-cli Awesomeness in Vancouver

It was great sharing the Awesome that is wp-cli with all of you at WordCamp Vancouver!

Huge thanks to the organizing team, Vanessa Chu, Joey Kudish, Morten Rand-Hendriksen and Angela Chih for the invitation to speak, and a great event.

If you have any additional questions, let me know, and I’ll append the post appropriately!

Included below are the slides and sample code used in the presentation for your perusal and notes.


Download slides as PDF

Code for “wp wcyvr backup” example command:

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( 'wcyvr', 'WCYVR_Backup_Command' );

/**
 * The WCYVR Backup Plugin
 *
 * @package WCYVR_Backup
 * @subpackage commands/community
 * @maintainer Mike Schroder
 */
class WCYVR_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 wcyvr backup [--no-db] [path/to/file]" );
	}
}

One thought on “wp-cli Awesomeness in Vancouver”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.