Skip to content

Instantly share code, notes, and snippets.

@HarishChaudhari
Last active March 20, 2017 14:46
Show Gist options
  • Save HarishChaudhari/952a9d270ee325ed5702 to your computer and use it in GitHub Desktop.
Save HarishChaudhari/952a9d270ee325ed5702 to your computer and use it in GitHub Desktop.
code to transfer from CPT to CPT
<?php
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 = 'mvpnavigators';
$post_type_2 = 'post';
// Delete all existing live plans prior to copying over preview plans
$query_live_plans_args = array(
'posts_per_page' => -1,
'post_type' => $post_type_2,
'post_status' => 'publish' );
$query_live_plans = new WP_Query( $query_live_plans_args );
if ( $query_live_plans->have_posts() ) {
while ( $query_live_plans->have_posts() ) {
$query_live_plans->the_post();
wp_delete_post( get_the_ID(), true);
}
}
$query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = '%s' ORDER BY post_date DESC", $post_type_1);
$posts = $wpdb->get_results($query, ARRAY_A);
$index = 0;
foreach($posts as $post){
$post_meta = '';
$terms = $term_list = array();
if($index >= 105){
die("Sucess fully completed $index.");
}
# 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);
$term_list = wp_get_post_terms($source_post_id, 'category');
foreach( $term_list as $t ) {
$terms[] = $t->term_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]);
if( isset( $terms ) && is_array($terms) ) {
$term_taxonomy_ids = wp_set_object_terms( $new_post, $terms, 'category' );
}
wp_delete_post($source_post_id);
$index = $index +1 ;
}
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;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment