From 8e3202c23b3d5726d1eb9165443a9d004c2e14a9 Mon Sep 17 00:00:00 2001 From: scribu Date: Thu, 19 Sep 2013 23:18:49 +0300 Subject: [PATCH] add --field arg to 'wp post get' --- features/post.feature | 2 +- php/commands/post.php | 40 ++++++++++++++++++++++++++++++---------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/features/post.feature b/features/post.feature index 8d6816ad..8b784471 100644 --- a/features/post.feature +++ b/features/post.feature @@ -50,7 +50,7 @@ Feature: Manage WordPress posts excerpt """ - When I run `wp post get --format=content {POST_ID}` + When I run `wp post get --field=content {POST_ID}` Then STDOUT should be: """ This is some content. diff --git a/php/commands/post.php b/php/commands/post.php index 5b8a7346..dc1d1d21 100644 --- a/php/commands/post.php +++ b/php/commands/post.php @@ -138,11 +138,13 @@ class Post_Command extends \WP_CLI\CommandWithDBObject { * * : The ID of the post to get. * + * [--field=] + * : Instead of returning the whole post, returns the value of a single field. The --format= + * parameter is ignored in this case. + * * [--format=] * : The format to use when printing the post, acceptable values: * - * - **content**: Outputs only the post's content. - * * - **table**: Outputs all fields of the post as a table. Note that the * post_content field is omitted so that the table is readable. * @@ -150,9 +152,8 @@ class Post_Command extends \WP_CLI\CommandWithDBObject { * * ## EXAMPLES * - * wp post get 12 --format=content - * - * wp post get 12 > file.txt + * # save the post content to a file + * wp post get 12 --field=content > file.txt */ public function get( $args, $assoc_args ) { $defaults = array( @@ -162,13 +163,32 @@ class Post_Command extends \WP_CLI\CommandWithDBObject { $post_id = $args[0]; if ( !$post_id || !$post = get_post( $post_id ) ) - \WP_CLI::error( "Failed opening post $post_id to get." ); + \WP_CLI::error( "Could not find the post with ID $post_id." ); - switch ( $assoc_args['format'] ) { + if ( isset( $assoc_args['field'] ) ) { + self::show_single_field( $post, $assoc_args['field'] ); + } else { + self::show_multiple_fields( $post, $assoc_args ); + } + } - case 'content': - WP_CLI::print_value( $post->post_content ); - break; + private function show_single_field( $post, $field ) { + $value = null; + + foreach ( array( $field, "post_$field" ) as $key ) { + if ( isset( $post->$key ) ) + $value = $post->$key; + } + + if ( null === $value ) { + \WP_CLI::error( "Invalid post field: $field." ); + } else { + WP_CLI::print_value( $value ); + } + } + + private function show_multiple_fields( $post, $assoc_args ) { + switch ( $assoc_args['format'] ) { case 'table': $fields = get_object_vars( $post ); -- 2.11.0