Going to explain this as best as possible. I'm working on a project, where we are building a WordPress based app. We have a user interface that includes a button to duplicate a post. However, this part always fails because of the nonce.
I have been able to create a nonce, but the nonce does not pass verification. I believe because I'm calling to duplicate the post from a page other than the admin.php page.
My question - is it possible to duplicate a post from another page and then get directed to the new draft post? Has anyone ever accomplished this before?
CodePudding user response:
Here is the code for the same. If you wish to change the post type while duplicating the page or post you may require to change one of the arguments. Please check my code and it's comments.
You need to call this function and pass the parameter of your post id.
function duplicate_post($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;
}