Wordpress - How do I clone or duplicate a post with the WordPress Command Line Interface WP-CLI?
This can now be done via WP-CLI using $ wp post create --from-post=1
. It even dupes the meta data.
Cloning a post via wp-cli is little trickier. It needs two steps:
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
Create new post from this file. In our scenario file.txt saved all information of
hello
post. Following command create a post namedduplicate
wp post create ./file.txt --post_title="duplicate"
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.