I took your code an minimized it, and made a .csv with 3 rows, and was able to get the same error as you.
However, I got three instances of the same post. No coincidence that I have 3 rows in my csv. Your insert code is right, so it has to be the hook being re-called each time the insert is fired.
I changed the hook to something seemingly random, but very specific for being user-end and admin-only, the admin_notices
hook, and it worked, no duplicate/triplicate entries made for the one page-load I enabled the code.
Although I don’t have documentation to prove this, I believe that many of the WordPress hooks re-fire with the wp_insert_post
call, and thats your problem.
// causes duplicates ---
//add_action('wp_loaded', 'add_from_csv', 10);
// no duplicates ---
//add_action('admin_notices', 'add_from_csv', 10);
function add_from_csv() {
if (($handle = fopen(dirname(__FILE__) . "/posts.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$post_id = wp_insert_post(
array(
'post_title' => $data[0],
'post_type' => 'post',
'post_status' => 'publish',
)
);
if(!is_wp_error($post_id) || $post_id != 0)
echo "<pre>Added {$data[0]}</pre>";
}
fclose($handle);
}
}
I would recommend creating a very simple admin settings/options page instead to house your code, and make the code fire from a form submit button, verified with nonce.