Wordpress:如何以编程方式创建帖子并在之前检查重复项

Wordpress: how to create posts programatically and check for duplications before

我有一个脚本可以从 API 中获取一些数据,我需要将这些数据(posts 的数组)作为 posts 插入 WordPress。

所以我需要做的是:

  1. 检查每个 post 是否存在,以避免被 post_name 配音 或 slugtitle 如果可能
  2. 我已经使用名为 newspaper 的 post 注册了自定义分类法 我需要在 title.
  3. 之前插入那份报纸
  4. 我还使用 post 注册了自定义字段,键是 fifu_img_urlfifu_img_alt_cmb_link 所以我需要一种方法来为每个 post
  5. 的这些键插入数据

这会在API post请求中休息,我已经完成了API部分并通过post请求接收数据,剩下的就是处理我在上面描述的数据。

我是通过以下方式完成的

$is_post_exists = post_exists($post->title);

if ($is_post_exists === 0) {
    $post_id = wp_insert_post(array(
        'post_title'    => $post->title,
        'post_date'     => $post->date,
        'post_content'  => $post->excerpt,
        'post_author'   => 1,
        'post_status'   => 'publish',
        'meta_input'    => array(
            'fifu_image_url'   => $post->image,
            'fifu_image_alt'   => $post->title,
            '_cmb_link'        =>  $post->link,
        )
    ));

    $termObj = get_term_by('name', $post->newspaper->title, 'newspaper');

    set_post_format($post_id, $post->type);

    if ($termObj) {
        wp_set_object_terms($post_id, array($termObj->term_id), 'newspaper');
    } else {
        $new_newspaper = wp_insert_term($post->newspaper->title, 'newspaper');

        wp_set_object_terms($post_id, array($new_newspaper['term_id']), 'newspaper');
    }

    if ($post_id) {
        $added_posts[] = $post_id;
    }
} else {
    $not_added_posts[] = $post->id;
}