Create WordPress posts from external API content

It is rather easy to build integrations and bring data to WordPress from external API. In most cases it’s also a good idea to save that data as posts to WordPress database. I also like to use WordPress CLI commands for this kind of integrations since it’s easy to schedule. You can off course use any trigger mechanism that suites your purpose (for example one of the hundreds of WordPress action hooks). This is a simple example how to do that.

First we check that WordPress CLI exists. Then we start writing our function that will fetch data from API and set is as a published post in WordPress database.

Get data

We can use example placeholder API and get data from there using WordPress built in get function ‘wp_remote_get’.  We pass some basic http arguments to it and encode and decode the response to get PHP variable to handle.

Check post does not exist allready

Since in this case we get back array we can loop items in array with foreach. Inside our loop we then check if we have previosly allready saved this post to database by using meta id we set for each post on creation.

Insert new post

If post does not exists yet we set our post object from item data and use ‘wp_insert_post’ function to add it to database.

Register CLI command

After our function we will create a new WP CLI command and set that if I call ‘wp jst-update-data’ on root folder of our site it will call this function we just wrote.

<?php

if(!class_exists('WP_CLI'))
return;
function update_data_from_external_api(){

      $response = wp_remote_get('https://jsonplaceholder.typicode.com/posts', $args );
      $response = json_encode($response); // Takes a mixed value and converts it to JSON string
      $data = json_decode($response); // Convert JSON string to PHP variable

      global $wp_version;

      $args = array(
      'timeout'     => 5,
      'redirection' => 5,
      'httpversion' => '1.0',
      'user-agent'  => 'WordPress/' . $wp_version . '; ' . home_url(),
      'blocking'    => true,
      'body'        => null,
      'compress'    => false,
      'decompress'  => true,
      'sslverify'   => false,
      'stream'      => false,
      'filename'    => null
      );

      foreach ($data as $item) {        
          // Check if post exist allready in WP
          $existing_posts = get_posts( array('post_type' => 'post', 'numberposts' => -1) );         
          $api_ids = array();
          foreach($existing_posts as $post) {
            $id = get_post_meta( $item->ID, 'api_id', true );
            array_push($api_ids, $id);
          }
          
          if(in_array($item->id, $api_ids )) {
            error_log('post allready exists');
          } else {

            // New post data object to set as a post
              $new_post = array(
                'post_type'     => 'post',
                'post_title'    => $item->title,
                'post_status'   => 'publish',
                'post_author'   => 1,
                'post_content'  => $item->body,
                'meta_input' => array(
                  'api_id' => $item->id,
              )
              );
              
              // Insert the post into the database
              wp_insert_post($new_post);
          }
      }  
}

WP_CLI::add_command('jst-update-data', 'update_data_from_external_api');