WordPress Cron Job 导入帖子

WordPress Cron Job import posts

我正在构建一个站点以从 JSON 提要中导入产品,然后将它们显示为我站点中的帖子。

我每天凌晨 3 点使用 cron 作业 运行 导入,但我对所有设置有疑问。

导入提要、根据提要创建帖子然后在网站上填充帖子是否是一种好做法?

要删除重复项,我会 运行 数据库检查产品 ID 并跳过那些已经创建的产品。

我对 cron 和动态创建帖子真的很陌生,所以我不确定这是否是最好的方法。

我通过向我的 functions.php 添加一个 AJAX 处理程序来解决它,通过 curl 请求获取作业,然后遍历提要将新帖子插入数据库并更新现有帖子。

//CURL request to fetch feed when getting AJAX call
function import_feed() {
  $url = "http://url-to-jsonfeed.com";

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  $data = json_decode($response, true);
  create_posts($data);
  wp_die();
}
add_action('wp_ajax_import_feed', 'import_feed');

//Loop through JSON data and create post 
function create_posts($jsonfeed) {
  $data = $jsonfeed['Report'];

  if (!empty($data) ) {
    foreach ($data as $entry) {

      //Set post data before creating post
      $post_data = array( 
        'post_title' => $entry['Entry_Title'],
        'post_name' => $entry['EntryID'], 
        'post_status' => 'publish', 
        'post_author' => 1,
        'post_type' => 'entries'
      );

      if (get_page_by_title($post_data['post_title'], 'entries') == null && empty(get_posts(array('post_type' => 'entries', 'name' => $post_data['post_name'])))) {
        wp_insert_post($post_data, $wp_error);

      } else if (!empty(get_posts(array('post_type' => 'entries', 'name' => $post_data['post_name'])))) {
        $post = get_posts(array('post_type' => 'entries', 'name' => $post_data['post_name']));
        $post_id = $post[0]->ID;
        $post_data['ID'] = $post_id;
        wp_update_post($post_data, $wp_error);
      }

    }
  }
}