Search code examples
phpwordpresscustom-post-type

Using wp_insert_post() - creates duplicates


I am adding one CPT to another CPT dynmaically. When using wp_insert_post() it creates duplicates when I add_action('init', 'function_name'); Any idea what hook to use to simply add them:

function cpt_to_cpt(){    
// Grab posts
    $args =  array(
        'post_type'     => ' custom_type1 ',
        'order'         =>  'ASC',
        'post_status'   =>  'publish',
        'numberposts'   => -1,
        );

    $posts = get_posts($args);

    foreach ( $posts as $post ) {  
        wp_insert_post(array(
            'post_type'     =>  'custom_type2',
            'post_title'    =>  $post->post_title,
            'post_date'     =>  $post->post_date,
            'post_author'   =>  $post->post->author,
            'post_status'   =>  'publish',
            )
         );
      }
add_action('init', 'cpt_to_cpt');

Solution

  • Try using:

    wp_loaded

    add_action('wp_loaded', 'cpt_to_cpt');
    

    or

    wp

    add_action('wp', 'cpt_to_cpt')