Reputation: 3585
I want to duplicate some posts programmatically without comments.
Does WordPress have a built-in function to duplicate posts?
Upvotes: 4
Views: 4156
Reputation: 2049
If you need to only copy the post, you can use @ngearing's solution in https://stackoverflow.com/a/56437515/3480821
If you want to duplicate the post with its meta and terms as well, you can use the following function:
<?php
/**
* Duplicates a post & its meta and returns the new duplicated Post ID.
*
* @param int $post_id The Post ID you want to clone.
* @return int The duplicated Post ID.
*/
function duplicate_post(int $post_id): int
{
$old_post = get_post($post_id);
if (!$old_post) {
// Invalid post ID, return early.
return 0;
}
$title = $old_post->post_title;
// Create new post array.
$new_post = [
'post_title' => $title,
'post_name' => sanitize_title($title),
'post_status' => 'draft',
'post_type' => $old_post->post_type,
];
// Insert new post.
$new_post_id = wp_insert_post($new_post);
// Copy post meta.
$post_meta = get_post_custom($post_id);
foreach ($post_meta as $key => $values) {
foreach ($values as $value) {
add_post_meta($new_post_id, $key, maybe_unserialize($value));
}
}
// Copy post taxonomies.
$taxonomies = get_post_taxonomies($post_id);
foreach ($taxonomies as $taxonomy) {
$term_ids = wp_get_object_terms($post_id, $taxonomy, ['fields' => 'ids']);
wp_set_object_terms($new_post_id, $term_ids, $taxonomy);
}
// Return new post ID.
return $new_post_id;
}
I have also made this function available in a Github gist here.
Upvotes: 2
Reputation: 1365
You can use the wp_insert_post()
function to duplicate a post.
You just need to remove the post ID from the data you pass to it, and Wordpress will create a new post instead of updating an existing one. E.g.
$post_id = 1234;
$post = (array) get_post( $post_id ); // Post to duplicate.
unset($post['ID']); // Remove id, wp will create new post if not set.
wp_insert_post($post);
Comments are stored in a different table. And are linked by the post ID. As the duplicate post will have a different ID the original comments will not be associated with it.
Upvotes: 4
Reputation: 970
No, there does not exists such functionality like duplicate post in WordPress core.
To meet your requirement you can use this plugin : https://wordpress.org/plugins/post-duplicator/
This plugin duplicate the post but not comment. See there documentation
Upvotes: 0