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.