1

I'm making a plugin that needs to change post content before the scheduled post is published.

The post is first stored as scheduled, then when it changes its status from scheduled(future) to published(publish), I need to send a request to an API, get a response from it and insert the API response in the post content.

The thing is that I want the status transition to "wait" for the response - not show the post as published UNTIL the API response is inserted in the post content.

Thank you!

0

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 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.