'How to prevent duplicate posts with wp_insert_post?

How to prevent duplicate posts with wp_insert_post on single.php?

My code is

$post_id = wp_insert_post( array(
  'post_status' => 'publish',
  'post_type' => 'post',
  'post_title' => 'Test Shop1',
  'post_content' => 'Lorem ipsum'
) );

$post_type = 'shop';
$query = "UPDATE {$wpdb->prefix}posts SET post_type='".$post_type."' WHERE id='".$post_id."' LIMIT 1";
GLOBAL $wpdb; 
$wpdb->query($query);

But every time i refresh it will added duplicate post..How will i prevent this?please help



Solution 1:[1]

$post_title = 'Test Shop1';
if (!post_exists($post_title)) { // Determine if a post exists based on title, content, and date
    $post_id = wp_insert_post(array(
        'post_status' => 'publish',
        'post_type' => 'post',
        'post_title' => $post_title,
        'post_content' => 'Lorem ipsum'
            ));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mujuonly