How to call a REST endpoint when a post is published?

You don’t have to write a new plugin. You can either add the code to your theme’s functions.php file, or create a child theme.

To wrap your data in a JSON format, you can use the json_encode function. Hook into the post when it’s published, and send the data. In the following function, i will send the post’s title, excerpt and featured image URL to the endpoint.

add_action('publish_post', 'call_the_endpoint',10,2);
function call_the_endpoint($post_id, $post){
    // Define an empty array
    $data = array();
    // Store the title into the array
    $data['title'] = get_the_title();
    // If there is a post thumbnail, get the link
    if (has_post_thumbnail()) {
        $data['thumbnail'] = get_the_post_thumbnail_url( get_the_ID(),'thumbnail' );
    }
    // Get the excerpt and save it into the array
    $data['excerpt'] = get_the_excerpt();
    // Encode the data to be sent
    $json_data = json_encode($data);
    // Initiate the cURL
    $url = curl_init('YOUR API URL HERE');
    curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($url, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($url, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json_data))
    );
    // The results of our request, to use later if we want.
    $result = curl_exec($url);
}

It would be possible to write an accurate answer if you could provide more information about your API and how you interact with it. However this was a simple example for you to know how to use the publish_post hook to achieve what you are looking for.

Leave a Comment