Here’s what you can do:
You can trigger an action when the post’s status is changing from future
to publish
, which happens when the scheduled time arrives. Then, change it’s status to draft, and make a request to the API. If the API replied, you can store the reply’s content and publish the post. If not, then schedule it again.
function api_request_transition( $new_status, $old_status, $post ) {
// Let's check for draft too, since we will set the status to draft if the API doesn't reply
if ( ($old_status =='future' || $old_status =='draft') && $new_status =='publish' ) {
// Set the status to draft for now
$current_post = array(
'ID' => $post->ID,
'post_title' => $post->post_title,
'post_status' => 'draft',
);
wp_update_post( $current_post );
// Get the content from the API
$api_data = file_get_contents('URL HERE');
// If the content is valid, add it to the post and publish it
if ($api_data) {
$my_post = array(
'ID' => $post->ID,
'post_title' => $post->post_title,
'post_content' => $api_data,
'post_status' => 'publish',
);
wp_update_post( $my_post );
// If the API didn't answer, run this process again in 5 minutes
} else {
// Pass the data to the cron job
$args = (
$new_status,
$old_status,
$post ,
);
// Schedule this again for 5 minutes later
wp_schedule_single_event(time() + 300 , 'api_repeat_request', $args);
}
}
}
add_action( 'transition_post_status', 'api_request_transition', 10, 3 );
add_action( 'api_repeat_request', 'api_request_transition',1 ,3 );