1

I know that I can clone or duplicate a post with several plugins. The one I use most often is https://wordpress.org/plugins/duplicate-post/. However I am using the WP-CLI more and more lately and I would like to be able to duplicate or clone a post from the command line.

Any suggestions would be appreciated.

5

Cloning a post via wp-cli is little trickier. It needs two steps:

  1. Create a file where save the information of post. Suppose, following command create a file named file.txt from hello post (id 1). In this case file.txt which save on root directory.

    wp post get 1 > file.txt

  2. Create new post from this file. In our scenario file.txt saved all information of hello post. Following command create a post named duplicate

    wp post create ./file.txt --post_title="duplicate"

  • You got me on the right track thanks. Here is what I finally came up with wp post get 6815 --field=content | wp post create - --post_title="Duplicate Of Some Title" --post_status='publish' The "-" after wp post create says read the content from the standard input. The --field=content limits info to just the content field. – tfrangio Jan 20 '17 at 11:28
5

This can now be done via WP-CLI using $ wp post create --from-post=1. It even dupes the meta data.

2

Thanks a lot for your answer and @Mrinal and confirming it would work with a pipe @tfrangio.

I was interested too in copying the meta values from one post to the other, so after creating the post with the duplicate with the pipe:

wp post get 6815 --field=content | wp post create - --post_title="Title of dup" --post_status='draft'

After I get the ID of the new post, I passed the meta_keys which I was interested...

assuming 14 is the source post_ID and 21 the target post_ID, I want to copy tie_hide_related and tie_sidebar_pos:

for meta_key in tie_hide_related tie_sidebar_pos ; \
do wp post meta get 14 $meta_key | \
xargs wp post meta update 21 $meta_key \
; done

xargs is needed to pass the value returned by post-meta-get to wp post-meta update, even if the documentation says it reads from stdin, without xargs some single values are read as an one item list, thus changing the behaviour of the value

Then, to copy the terms of a taxonomy, let's say category:

 for cat_id in `wp post term list 14 category --format=ids` ; \
 do wp post term add 21 category $cat_id --by=id ; done

This last step could be repeated for several taxonomies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.