Skip to content

Instantly share code, notes, and snippets.

@smartrashed
Forked from eduwass/duplicate-post.php
Created February 25, 2020 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smartrashed/d39b2d4655d831b0fb35465fcf7e4f49 to your computer and use it in GitHub Desktop.
Save smartrashed/d39b2d4655d831b0fb35465fcf7e4f49 to your computer and use it in GitHub Desktop.
Programmatically duplicating a WordPress post
<?php
/**
* Duplicates a post & its meta and it returns the new duplicated Post ID
* @param [int] $post_id The Post you want to clone
* @return [int] The duplicated Post ID
*/
function duplicate($post_id) {
$title = get_the_title($post_id);
$oldpost = get_post($post_id);
$post = array(
'post_title' => $title,
'post_status' => 'publish',
'post_type' => $oldpost->post_type,
'post_author' => 1
);
$new_post_id = wp_insert_post($post);
// Copy post metadata
$data = get_post_custom($post_id);
foreach ( $data as $key => $values) {
foreach ($values as $value) {
add_post_meta( $new_post_id, $key, $value );
}
}
return $new_post_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment