Title: Automatically create posts with REST API
Last modified: September 16, 2018

---

# Automatically create posts with REST API

 *  [portia79](https://wordpress.org/support/users/portia79/)
 * (@portia79)
 * [7 years, 11 months ago](https://wordpress.org/support/topic/automatically-create-posts-with-rest-api/)
 * Hi,
 * I’m just starting with WP rest API so have a very basic understanding of it.
 * I have been able to retrieve categories, custom post types, etc, process their
   json data to display them how I wanted but that’s it.
 * I have created a custom post type (“Announcements”) with custom taxonomy terms(
   eg. Meetings, Events, etc) associated with this particular post type. Now, I 
   have been asked to automatically pull some data from our other website and integrate
   them into Announcements. I’m able to use the other website API and display the
   needed data on our WordPress page. The problem is I’d like to automatically create
   the actual posts, assign them to relevant categories in my Announcement system.
 * Is it possible? Where would I start?
 * Thank you

Viewing 5 replies - 1 through 5 (of 5 total)

 *  [Santiago](https://wordpress.org/support/users/sjaure/)
 * (@sjaure)
 * [7 years, 11 months ago](https://wordpress.org/support/topic/automatically-create-posts-with-rest-api/#post-10694045)
 * Hi [@portia79](https://wordpress.org/support/users/portia79/),
 * Hope you are doing well.
    I’m a bit confused with the diferent pieces involved
   in your system. I understand that you are already able to pull the data from **
   WP site A** into **WP site B** and that you are parsing it and rendering directly
   into the view. Is that correct?
 * If that’s the case, and the challenge is to ‘migrate’ several posts from **site
   A** into **site B** but converting those to the cpt ‘Announcements’, I would 
   suggest the following:
 * Create a plugin that will be installed in **site B**, there you will implement
   a REST call to **site A** to get the list of posts and then you will loop through
   the list.
    In that loop, you will make use of the method [wp_insert_post()](https://developer.wordpress.org/reference/functions/wp_insert_post/).
   When defining the data array for wp_insert_post, you will set the post_type to‘
   Announcements’. You will also use the method [wp_set_object_terms()](https://codex.wordpress.org/Function_Reference/wp_set_object_terms)
   to attach the corresponding custom taxonomy.
 * Did I get the question right? I hope so 🙂
 * Have a great day
    -  This reply was modified 7 years, 11 months ago by [Santiago](https://wordpress.org/support/users/sjaure/).
 *  Thread Starter [portia79](https://wordpress.org/support/users/portia79/)
 * (@portia79)
 * [7 years, 11 months ago](https://wordpress.org/support/topic/automatically-create-posts-with-rest-api/#post-10694316)
 * Thank you for your reply [@sjaure](https://wordpress.org/support/users/sjaure/).
 * Your understanding of my situation is correct (apart from the fact that Site 
   A is not a WP site – but in this case, it shouldn’t matter, should it?). When
   you say to loop through the list of data from Site A, how do you mean? I loop
   over Site A data in the following way (and therefore, not sure how to insert 
   wordpress/php functions/statements in that):
 *     ```
       jQuery.ajax({
           url: urlr,
           method: "GET",
           dataType: 'json',
           success: function(data) {
               console.log(data);
               var html_to_append = '';
               jQuery.each(data.events, function(i, item) {
                   s = item.start_date.substring(0, item.start_date.indexOf('T'));
                   html_to_append +=
                       '<div class="col-md-2 mb-2 bg-light d-flex align-items-center justify-content-center"><div class="text-center pt-1"><h5>' +
                       s + '</h5></div></div>' +
                       '<div class="col-md-7 p-2 "><h3>' +
                       item.name + '</h3><p>' +
                       item.type + '</p><p>Fee: ' + item.entrylists[0].fees[0].amount + '</p></div><div class="col-md-3 d-flex align-items-center justify-content-center"><a class="btn btn-primary" href="' + item.enter_uri + '" role="button" target="_blank">Book Event</a></div>';
               });
               jQuery("#riderhq").html(html_to_append);
           },
           error: function() {
               console.log(data);
           }
       });
       ```
   
 * Once again, thank you for your response.
 * Have a lovely day!
 *  [Santiago](https://wordpress.org/support/users/sjaure/)
 * (@sjaure)
 * [7 years, 11 months ago](https://wordpress.org/support/topic/automatically-create-posts-with-rest-api/#post-10697533)
 * Oh! You are consuming the REST API from JS. Didn’t get that part clear before.
 * In this case, it doesn’t make sense to use JS since it runs in the client side.
   You would need to hit and endpoint in site B to create the post, and you will
   need to deal with security.
    Not practical.
 * I recommend to connect to site A from within WordPress server, using PHP.
    Here
   you will find a nice tutorial on how to do it. [https://pippinsplugins.com/using-wp_remote_get-to-parse-json-from-remote-apis/](https://pippinsplugins.com/using-wp_remote_get-to-parse-json-from-remote-apis/)
 * Sorry for the delay on my response. Let me know if you have further questions
   and I’ll try to address it as soon as I can.
 * Take care!
 *  Thread Starter [portia79](https://wordpress.org/support/users/portia79/)
 * (@portia79)
 * [7 years, 11 months ago](https://wordpress.org/support/topic/automatically-create-posts-with-rest-api/#post-10702150)
 * Thank you. I’ve managed to rewrite it to get the data using php as per the article
   you linked. Now, I’ll attempt to put all the pieces together and will report 
   once/if done:)
 *  Thread Starter [portia79](https://wordpress.org/support/users/portia79/)
 * (@portia79)
 * [7 years, 11 months ago](https://wordpress.org/support/topic/automatically-create-posts-with-rest-api/#post-10709384)
 * OK. I’m stuck again. I seem to be able to insert posts but, now everytime the
   code is executed, the same posts get added resulting in multiple duplicates.
 * 1. First of all, just to clarify, I’m adding all this code in a page template.
   Eventually, the page will display those ‘events’ in a nice fashion. I assume,
   none of the code should go to functions.php? The code below just lists the posts/
   events in a simple list for the sake of testing (and inserts them to the WP database).
   
   2. How do I prevent them from re-inserting each time the page is refreshed. The
   only unique thing is a post/event id (a string like ‘k3afke2kr’), which can be
   accessed in the code below via $event[‘id’]. Even the ‘title’ might not be unique
   as there are weekly/monthly events of the same title.
 *     ```
       <?php 
         $request = wp_remote_get( 'https://api.riderhq.com/api/v1/3446/getevents?pretty=true' );
   
         if( is_wp_error( $request ) ) {
           echo "wrong request";
           return false; // Bail early
         }
   
         function utf8ize($mixed) { 
           if (is_array($mixed)) { 
           foreach ($mixed as $key => $value) { 
           $mixed[$key] = utf8ize($value); 
           } 
           } else if (is_string ($mixed)) { 
           return utf8_encode($mixed); 
           } 
           return $mixed; 
           }
   
         $body = wp_remote_retrieve_body( $request ); 
         $data = json_decode(utf8ize($body), true); 
         $data_events = $data['events'];
         print_r($data_events); // prints ok -
   
         if( ! empty( $data_events ) ) {
           echo '<ul>';
       	    foreach( $data_events as $event ) {
   
               echo '<li>';
               echo $event['id'];
       			    echo '<a href="' . esc_url( $event['uri'] ) . '">' . $event['name'] . '</a>';
               echo '</li>';
   
               $new_post = array(
                 'post_title' => $event['name'],
                 'post_content' => 'description',
                 'post_status' => 'publish',
                 'post_author' => '2',
                 'post_type' => 'post',
                 'post_category' => array(1),
             );
             wp_insert_post($new_post);
   
   
       	    }
       	  echo '</ul>';
         }
   
       ?>
       ```
   
 * Thank you very much for the support.

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘Automatically create posts with REST API’ is closed to new replies.

 * In: [Developing with WordPress](https://wordpress.org/support/forum/wp-advanced/)
 * 5 replies
 * 2 participants
 * Last reply from: [portia79](https://wordpress.org/support/users/portia79/)
 * Last activity: [7 years, 11 months ago](https://wordpress.org/support/topic/automatically-create-posts-with-rest-api/#post-10709384)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
