Skip to content

Commit e9fb3c6

Browse files
committed
create subcommand extended to generate duplicate post
1 parent 334ec3d commit e9fb3c6

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

src/Post_Command.php

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,10 @@ public function __construct() {
7777
*
7878
* [--post_name=<post_name>]
7979
* : The post name. Default is the sanitized post title when creating a new post.
80-
*
80+
*
81+
* [--from-post=<post_id>]
82+
* : The post id of a post to be duplicated.
83+
*
8184
* [--to_ping=<to_ping>]
8285
* : Space or carriage return-separated list of URLs to ping. Default empty.
8386
*
@@ -147,7 +150,11 @@ public function __construct() {
147150
* # Create a post with multiple meta values.
148151
* $ wp post create --post_title='A post' --post_content='Just a small post.' --meta_input='{"key1":"value1","key2":"value2"}
149152
* Success: Created post 1923.
150-
*/
153+
*
154+
* # Create a duplicate post with same post data.
155+
* $ wp post create --from-post=123 --post_title='Different Title'
156+
* Success: Created post 2350.
157+
*/
151158
public function create( $args, $assoc_args ) {
152159
if ( ! empty( $args[0] ) ) {
153160
$assoc_args['post_content'] = $this->read_from_file_or_stdin( $args[0] );
@@ -173,6 +180,21 @@ public function create( $args, $assoc_args ) {
173180
$array_arguments = array( 'meta_input' );
174181
$assoc_args = \WP_CLI\Utils\parse_shell_arrays( $assoc_args, $array_arguments );
175182

183+
if( isset( $assoc_args['from-post'] ) ) {
184+
$post = $this->fetcher->get_check( $assoc_args['from-post'] );
185+
$post_arr = get_object_vars( $post );
186+
$post_id = $post_arr['ID'];
187+
unset( $post_arr['post_date'] );
188+
unset( $post_arr['post_date_gmt'] );
189+
unset( $post_arr['guid'] );
190+
191+
if ( empty( $assoc_args['meta_input'] ) ) {
192+
$assoc_args['meta_input'] = $this->get_metadata( $post_id );
193+
}
194+
195+
$assoc_args = array_merge( $post_arr, $assoc_args );
196+
}
197+
176198
$assoc_args = wp_slash( $assoc_args );
177199
parent::_create( $args, $assoc_args, function ( $params ) {
178200
return wp_insert_post( $params, true );
@@ -797,4 +819,22 @@ private function get_category_ids( $arg ) {
797819
// If no category ids found, return exploded array for compat with previous WP-CLI versions.
798820
return $category_ids ? $category_ids : $categories;
799821
}
822+
823+
/**
824+
* Get post metadata.
825+
*
826+
* @param $post_id id of the post.
827+
* @return array
828+
*/
829+
private function get_metadata( $post_id = null ) {
830+
$metadata = get_metadata( 'post', $post_id );
831+
$items = array();
832+
foreach ( $metadata as $key => $values ) {
833+
foreach ( $values as $item_value ) {
834+
$item_value = maybe_unserialize( $item_value );
835+
$items[ $key ] = $item_value;
836+
}
837+
}
838+
return $items;
839+
}
800840
}

0 commit comments

Comments
 (0)