我一直致力于一个插件,其中涉及自定义帖子类型。这种类型的每个帖子都有一个'time‘元键,它是我使用wp_insert_post和add_post_meta在帖子中创建的:
foreach ($place->result->reviews as $review) {
//first check if the post exists using the meta data
$query_meta = array(
'post_type' => 'testimonials',
'meta_query' => [
'meta_key' => 'time',
'meta_value' => "$review->time"]
);
$time_posts = new WP_Query($query_meta);
if ($time_posts->post_count == 0) {
//iterate the reviews module into the Total Testimonials Custom Post Type
$post_id = wp_insert_post(array(
'post_type' => 'testimonials',
'post_title' => 'Review ' . $review->time,
'post_content' => $review->text,
'post_excerpt' => $review->text,
'post_thumbnail' => $review->profile_photo_url,
'post_author' => $review->author_name,
'post_status' => 'draft',
'comment_status' => 'closed', // if you prefer
'ping_status' => 'closed', // if you prefer
));
add_post_meta($post_id, 'time', "$review->time");
add_post_meta($post_id, 'post_rating', $review->rating);
add_post_meta($post_id, 'testimonial_author', $review->author_name);
add_post_meta($post_id, 'thumbnail', $review->profile_photo_url);
}
}每次插件执行时(在wp-cron事件上),它应该从源代码中拉下任何新的证明,然后通过循环检查逐个解析它们,以查看是否存在具有相同时间的post,如果存在,则不应该发生插入-如果不存在,则应该以上述方式插入新的证明。
我已经尝试了3种方式来检查现有帖子的存在:
$query_meta = array(
'posts_per_page' => -1,
'post_type' => 'testimonials',
'meta_query' => array(
array(
'key' => 'time',
'value' => $review->time,
'compare' => '='
),
)
);
$post = query_posts($query_meta);
if (count($post) == 0) // insert我也尝试过这种方法:
$posts = get_posts(['meta_key' => 'time', 'meta_value' => $review->time]);
if (count($posts) == 0) // insert最后是这样的:
$query_meta = array(
'posts_per_page' => -1,
'post_type' => 'testimonials',
'meta_query' => array(
array(
'key' => 'time',
'value' => $review->time,
'compare' => '='
),
)
);
$post = new WP_Query($query_meta);
if ($post->have_posts() == FALSE) //insert每次尝试时,我都会得到自定义帖子类型的重复帖子。有人能告诉我我哪里做错了吗?在我看来,检查一个帖子是否存在并不是一件困难的事情。所以我觉得我遗漏了一些明显的东西。
非常感谢您的帮助。
发布于 2018-01-19 09:08:07
因此,在尝试了我能想到的所有方法之后,我最终通过wpdb使用了一个直接的SQL查询。这似乎是我可以有效地确定包含自定义元数据的帖子是否存在的唯一方法:
$hasdata = $wpdb->get_results("select * from $wpdb->postmeta where meta_key='time' and meta_value='$review->time'");
if (count($hasdata) == 0) {
//insert data发布于 2018-01-18 22:46:46
我认为您不会希望使用$post变量设置WP_Query对象,因为它是WP原生的。我有以下幸运之处:
$query_meta = array(
'post_type' => 'testimonials',
'meta_key' => 'time',
'meta_value' => $review->time
);
$time_posts = new WP_Query( $query_meta );
if ( $time_posts->post_count == 0 ) {
echo 'insert things';
}https://stackoverflow.com/questions/48323090
复制相似问题