Wordpress在使用wp-insert-post之前检查并删除重复的帖子。从Json wp-remote-get解码的数据。我正在插入一个Custom Post类型,唯一的值是'feefo_id‘。
我尝试在wp-insert周围创建一个if循环,但当我这样做时,我得到了1个post,而不是所有的17个。
$feefo_data = wp_remote_get( 'https://api.feefo.com/api/10/reviews/all?enter code heremerchant_identifier=hide-and-seek-travel' );
$feefo_data_decode = json_decode( $feefo_data['body'] );
var_dump($feefo_data_decode);
foreach ( $feefo_data_decode->reviews as $item ) {
$feefo_id =$item->service->id;
$post_title = $item->service->title; // post title
$post_content = $item->service->review;
$feefo_display_names = $item->customer->display_name;
$feefo_display_location = $item->customer->display_location;
$feefo_rating = $item->service->rating->rating;
$my_post = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
'post_type' => 'feefo_reviews',
);
$post_id = wp_insert_post( $my_post );
update_field( 'feefo_display_names', $feefo_display_names, $post_id );
update_field( 'feefo_display_location', $feefo_display_location, $post_id );
update_field( 'feefo_rating', $feefo_rating, $post_id );
//feefo_id is unique
update_field( 'feefo_id', $feefo_id , $post_id );
}目前,上面的代码从feefo中提取数据,并添加到一个名为'feefo_reviews‘的自定义帖子中。你,当我再拉一次的时候,它是重复的。
我希望避免插入重复项。唯一id是$feefo_id,并被插入到名为feefo_id的ACF字段中
发布于 2019-05-15 21:27:01
一种解决方案是将feefo_id作为元值保存到创建的帖子中。在每次新的pull时,首先检查是否已经有具有该元值的post。如果为true:修改已有的post,否则:创建一个新post。
发布于 2019-05-16 16:10:55
我似乎已经解决了这个问题,但逻辑让我摸不着头脑。开始和结束WP-查询代码。如果有人有空闲时间,你能告诉我wp_query里发生了什么吗?
$my_post = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
'post_type' => 'feefo_reviews',
//Set feefo_id as meta to be called upon with wp_Query as setting it as ID did not work.
'meta_input' => array(
'feefo_id' => $feefo_id
)
);
$mg_args = array(
'post_type' => 'feefo_reviews',
'meta_query' => array(
array(
'key' => 'feefo_id',
'value' => $feefo_id,
)
)
);
$mg_query =new WP_Query( $mg_args );
if( $mg_query ->have_posts()){
$post_id = wp_insert_post( $my_post );
update_field( 'feefo_display_names', $feefo_display_names, $post_id );
update_field( 'feefo_display_location', $feefo_display_location, $post_id );
update_field( 'feefo_rating', $feefo_rating, $post_id );
//feefo_id is unique
update_field( 'feefo_id', $feefo_id , $post_id );
}
}https://stackoverflow.com/questions/56147835
复制相似问题