Search code examples
jsonwordpresscronfeed

WordPress Cron Job import posts


I am building a site to import products from an JSON feed, and then display them as posts in my site.

I am using a cron job to run an import every day at 3am, but I have a question regarding the setup of it all.

Would it be good practice to import the feed, create posts based on the feed and then populate the posts on the site?

To remove duplicates I would run a DB check for the product ID and skip those that are already created.

I am really new to cron and dynamically creating posts so I am not sure if this is the best way to go about it.


Solution

  • I solved it by adding an AJAX handler to my functions.php, fetch the jobs through a curl request and then looping through the feed inserting new posts to DB and updating already existing posts.

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