【问题标题】:WordPress Cron Job import postsWordPress Cron Job 导入帖子
【发布时间】:2019-02-22 06:44:16
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 您是使用插件还是手动从 JSON 提要导入产品?
  • 我是手动做的,在我是如何解决的下面添加了评论。

标签: json wordpress cron feed


【解决方案1】:

我通过在我的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);
      }

    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 2018-04-13
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    相关资源
    最近更新 更多