Question

I have a custom PHP application and a Wordpress instance running as 2 completely separate codebases on the same server. I would like my custom PHP application to be able to consume content from the Wordpress instance as and when it is published or updated.

I am using the excellent WP API to retrieve JSON encoded Wordpress post(s) from my Wordpress instance. This plugin can retrieve all posts or an individual post (specified by id).

This currently involves actively polling the Wordpress instance for all posts and then figuring out which are new or have been modified, which is not ideal.

I would like Wordpress to notify my PHP application when a new post is created or updated. I realise there are numerous email notification plugins for Wordpress (the best one being Better Notifications for Wordpress). But I do not want the overhead of having to run an SMTP server and parsing email content.

I have been looking for a solution which simply uses REST to send a POST or GET request to my application, passing the ID of the (recently published or updated) Wordpress post. I am not aware of any built-in Wordpress functionality or plugins which exist to achieve this.

Was it helpful?

Solution

Use the HTTP API to send a "ping" on the wp_insert_post action, which is fired whenever a post is created/updated:

/**
 * @param   int     $post_id    The ID of the post.
 * @param   WP_Post $post       The post object.
 * @param   bool    $update     True if the post already exists and is being updated
 */
function wpse_185340_post_ping( $post_id, $post, $update ) {
    if ( $post->post_status === 'publish' ) { // Only fire when published
        wp_remote_post(
            'http://example.com/application/notify',
            array(
                // https://codex.wordpress.org/HTTP_API
                'blocking' => false, // If you don't need to know the response, disable blocking for an "async" request
                'body' => array(
                    'post_id' => $post_id,
                    'post'    => json_encode( $post ),
                    'update'  => ( int ) $update,
                    // or whatever
                )
            )
        );
    }   
}

add_action( 'wp_insert_post', 'wpse_185340_post_ping', 10, 3 );

OTHER TIPS

You can use WP's save_post action hook with extending WP-API plugin.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top