如何使用wp_insert_post防止重复帖子?

时间:2019-03-11 05:41:57

标签: php wordpress

如何防止single.php上带有wp_insert_post的重复帖子?

我的代码是

$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);

但是每次刷新时,都会添加重复的帖子。如何防止这种情况?请帮忙

1 个答案:

答案 0 :(得分: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'
            ));
}