I am trying to add posts of a custom post-type in bulk from a .csv file. Everything works except that it adds the post twice. They are exactly the same in the database except one has author 1 and the other has author 2. Also it appends a '-2' to post_name. Here is what I have:
add_action('wp_loaded', 'add_from_csv', 10);
function add_from_csv() {
if (($handle = fopen(dirname(__FILE__) . "/posts.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$term_1 = $data[0];
$term_2 = $data[1];
$term_3 = $data[2];
$term_4 = $data[3];
$term_5 = $data[4];
$meta_1 = $data[5];
$meta_2 = $data[6];
$meta_3 = $data[7];
$meta_4 = $data[8];
$meta_5 = $data[9];
$meta_6 = isset($data[10]) ? $data[10] : '';
$post_id = wp_insert_post(
array(
'post_title' => $meta_1 . ' ' . $meta_2 . ' ' . $meta_3 . ': ' . $meta_4,
'post_type' => 'custom_type',
'post_status' => 'publish',
)
);
if(!is_wp_error($post_id) || $post_id != 0) {
$tax_1_terms = array($term_1, $term_2, $term_3, $term_4);
wp_set_object_terms( $post_id, $tax_1_terms, 'tax_1' );
wp_set_object_terms( $post_id, $term_5, 'tax_2' );
update_post_meta($post_id, 'meta-1', $meta_1);
update_post_meta($post_id, 'meta-2', $meta_2);
update_post_meta($post_id, 'meta-3', $meta_3);
update_post_meta($post_id, 'meta-4', $meta_4);
update_post_meta($post_id, 'meta-5', $meta_5);
update_post_meta($post_id, 'meta-6', $meta_6);
} else {
echo 'There was a WP_Error when loading posts from csv!';
break;
}
}
fclose($handle);
}
}
I have this in a plugin by itself. If I don't set 'post_status', and it uses the default status of 'draft' then there are no duplicates. but when I set 'post_status' => 'publish' then it inserts the post twice. Both of the duplicates have status of publish. Can someone help me resolve this please? Thanks
wp_loaded
is a very generic hook that fires on every page ( including WP Crong which is loaded at the end of the page load ), you also never specify the post author, or check for duplicates