Skip to content

Instantly share code, notes, and snippets.

@HarishChaudhari
Last active August 17, 2021 12:13
Show Gist options
  • Save HarishChaudhari/ea4ec39670135b03babd to your computer and use it in GitHub Desktop.
Save HarishChaudhari/ea4ec39670135b03babd to your computer and use it in GitHub Desktop.
Copy posts from one Custom Post Type to another. (It doesn't handle post attachments for now)
<?php
add_action('admin_init', 'foo_duplicate_posts', 99999);
function foo_duplicate_posts(){
// Only allow admins to run the script
if(!current_user_can('manage_options'))
return;
// Check if keyword is set
if(!isset($_GET['duplicate-posts']))
return;
// Check if keyword matches
if($_GET['duplicate-posts'] !== 'magic-password')
return;
global $wpdb;
// Configure post types
$post_type_1 = 'post_type_one';
$post_type_2 = 'post_type_two';
$query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = '%s'", $post_type_1);
$posts = $wpdb->get_results($query, ARRAY_A);
foreach($posts as $post){
// Post info is already stored in an array
// Set the post_type to the new post type
$post['post_type'] = $post_type_2;
$source_post_id = $post['ID'];
unset($post['ID']); // Remove ID
unset($post['guid']); // Remove guid
// Insert new post
$new_post = wp_insert_post($post);
// Proceed if new post was created
if($new_post){
// Print a success message to the screen
//show_message("{$post['post_title']} was duplicated from #$post['ID'] to #$new_post");
show_message($post['post_title'] . " was duplicated from #" . $source_post_id ." to #".$new_post);
// Get source post's post meta
$post_meta = get_post_custom($source_post_id);
// Convert all postmeta to new post
if(is_array($post_meta))
foreach($post_meta as $k => $v)
update_post_meta($new_post, $k, $v[0]);
} else {
// Print an error message to the screen
show_message($post['post_title'] . " was not duplicated.");
}
}
// Stop the admin area from loading to get a clean reading of our output messages
exit;
}
?>
@HarishChaudhari
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment