I’m having a bit of a problem in WordPress. I’m looping through a set of data and creating new posts. I need a way to only create the post if its already not exists.
I tried this, but figured it was a quite stupid idea. But can i do something similar? I cant check the titles, since they in many cases will be the same. Can i do the check on import_id
somehow? If i do $post_id->import_id
its undefined..
Current code:
for($i = 0; $i < count($postdata); $i++) { //array of data.
$id = rand(1000, 9999);
if(is_null(get_post($id))) {
$post_id = wp_insert_post(array(
'import_id' => $id, //number
'post_status' => $post_status, //string
'post_type' => $post_type, //string
'post_title' => $post_title, //string
'post_content' => $post_content //string
));
}
}
2
Answers
You can use the
get_post_status()
function to tell if a post exists. It will return false if the post does not exist:With your example:
You can use post_exists() it will check based on title. check the code below.
Update as per OP code.