代码之家  ›  专栏  ›  技术社区  ›  user2868900

wordpress cron作业导入帖子

  •  0
  • user2868900  · 技术社区  · 6 年前

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

    我每天凌晨3点都在使用cron作业来运行导入,但我有一个关于这一切设置的问题。

    导入提要、基于提要创建文章,然后填充网站上的文章,这是一个好的实践吗?

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

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

    1 回复  |  直到 6 年前
        1
  •  0
  •   user2868900    6 年前

    我通过在functions.php中添加一个Ajax处理程序来解决这个问题,通过curl请求获取作业,然后通过feed循环将新的文章插入到db中,并更新已经存在的文章。

    //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);
          }
    
        }
      }
    }