WordPress Publish Post Hook

As I have mentioned in our technology stack article, we use WordPress to manage our content. Our front-end is handled and served using Node and MongoDB stack and I needed to connect these two systems (WordPress and custom Node stack) without making any large dependencies.

One of the old school ways is to create a job scheduler which looks for changes in the WordPress periodically and create/update content in local MongoDB.

I don’t like this approach at all. Instead, I was looking for something event-based i.e when we publish a new article or update the article, WordPress generates an event and allows us to write our business logic after the event.

I found WordPress publish hooks to be the solution.

Here is my live WordPress publish hook. This code should be placed in the functions.php.

// add action
add_action( 'post_updated', 'post_update_function', 10, 3 );

function post_update_function( $post_ID, $post_after, $post_before ) {
    // on each change, call this api to notify the content engine
    $event = null;
    // if article is auto draft
    if($post_before -> post_status === 'auto-draft' && $post_after -> post_status === 'publish') {
        $event = 'new_article';
    // if article is draft then published
    } else if($post_before -> post_status === 'draft' && $post_after -> post_status === 'publish') {
        $event = 'new_article';
    // if its updated article
    } else if($post_before -> post_status === 'publish' && $post_after -> post_status === 'publish') {
        $event = 'updated_article';
    } else {
        return;
    }
    if($event === null) {
        return;
    }
    $response = wp_remote_post('----custom API end point ------', array(
        'method' => 'POST',
        'body' => array('eventType' => $event, 'postId' => $post_ID )
    ));
}

As you can see in the code shown above, whenever we create or update a post, a new event will be triggered that will in turn call post_update_function function.

You can write any custom business logic inside the function. I wrote a code that calls the API exposed by the Node server.

I have also wrapped this in a nice and clean WordPress plugin. Click here to visit the repository.

Further study