How to update API data saved to database at regular intervals

Question

If I run the wordpress cron I insert data from the API for a custom post type using advanced custom fields.

However, if I run it again it obviously duplicates the data which I don’t want.

If the API itself had an ‘updated at’ field I could try and update by newer date but it doesn’t have that. Is there a way I can still check if records from the API are newer and then either add any new ones and update old ones.

Or, do I have to delete everything and add them all again every time the cron runs?

function get_data_from_api() {

     $locations = [];

     $results = wp_remote_retrieve_body(wp_remote_get('https://myAPI/v1/locations'));
     $results = json_decode($results);

     if ( ! is_array( $results ) || empty( $results ) ) {
        return false;
     }

     $locations[] = $results;

     foreach ($locations[0] as $location) {
            $inserted_location = wp_insert_post([
                'post_name' => $location->City,
                'post_title' => $location->City,
                'post_type' => 'location',
                'post_status' => 'publish'
            ]);

              if (is_wp_error( $inserted_location ) ) {
                continue;
            }

            $fillable = [
                'field_5ddfd334b1dee' => 'Address1',
                'field_5ddfd346b1def' => 'Address2',
                'field_5ddfd353b1deg' => 'Address3',
                'field_5ddfd35fb1deh' => 'Address4',
                'field_5ddfd35fb1dei' => 'City'

            ];

             foreach( $fillable as $key => $name ) {
                 update_field( $key, $location->$name, $inserted_location );
            }
     }
}

if (!wp_next_scheduled('update_locations')) {
    wp_schedule_event(time(), 'hourly', 'update_locations');

}
add_action('update_locations', 'get_data_from_api');
0
, , , user8463989 4 years 2019-11-29T04:42:26-05:00 0 Answers 89 views 0

Leave an answer

Browse
Browse