How to check if the post exists before wp_insert_post to avoid duplication?
The code below works if I remove the 'if' statement (post_exists()) and just keep reinserting posts producing multiple duplications. I wrote the if-statement with post_exists() just to start implementing the logic of checking but the moment I add the if statement, something breaks and the list below doesn't even get printed.
$body = wp_remote_retrieve_body( $request );
$data = json_decode(utf8ize($body), true);
$data_events = $data['events'];
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
// the if statement below seems to break things ie. no li below printed.
if ( post_exists( $event['name'] ) == 0 ) {
echo 'exists';
} else {
echo 'doesnt exist';
}
echo '<li>';
echo $event['id'];
echo '<a href="' . esc_url( $event['uri'] ) . '">' . $event['name'] . '</a>';
echo '</li>';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'post',
'post_category' => array(1),
'meta_input' => array(
'hq_id' => $event['id'],
)
);
//wp_insert_post($new_post); // commented out while testing the if statement.
}
echo '</ul>';
}
?>
Edit: please see the $data_events array: https://pastebin.com/rC60iNyJ
The post_exists() function is not normally available on the front end. Instead of including another file you can use get_page_by_title to find a post by it's title. Just test for a null value to check if it doesn't exist.
Replace
if ( post_exists( $event['name'] ) == 0 ) {
with
if ( get_page_by_title( $event['name'] ) == null ) {
Try this code. you need to include this file.
because post_exists function will work on admin page not in frontend.
if ( ! is_admin() ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode(utf8ize($body), true);
$data_events = $data['events'];
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
// the if statement below seems to break things ie. no li below printed.
if ( post_exists( $event['name'] ) == 0 ) {
echo 'doesnt exist';
} else {
echo 'exists';
}
echo '<li>';
echo $event['id'];
echo '<a href="' . esc_url( $event['uri'] ) . '">' . $event['name'] . '</a>';
echo '</li>';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'post',
'post_category' => array(1),
'meta_input' => array(
'hq_id' => $event['id'],
)
);
//wp_insert_post($new_post); // commented out while testing the if statement.
}
echo '</ul>';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With