wp-insert-post创建重复项

时间:2019-05-15 11:04:38

标签: json wordpress post

WordPress使用wp-insert-post之前,检查并删除重复的帖子。从Json wp-remote-get解码的数据。我正在插入“自定义帖子”类型,并且唯一值是“ feefo_id”。

我曾尝试在wp-insert周围创建一个if循环,但是当我这样做时,我得到了1条帖子,而不是全部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字段中

2 个答案:

答案 0 :(得分:1)

一种解决方案是将feefo_id作为元值保存到创建的帖子中。在每次进行新拉动时,您首先要检查是否已经有一个具有该元值的帖子。如果为true:修改现有帖子,否则:创建新帖子。

答案 1 :(得分:0)

我似乎已经解决了问题,但逻辑使我难以理解。 起始和结束WP-Query代码。如果某人有空闲时间,您能否通过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 );
}
}