Would you like to send your published WordPress posts to external services via webhooks or API? Send published posts to an online automation tool such as Zapier, automate.io to automate tasks?

Here’s are the list of key features we’ll accomplish after the tutorial:

Features

Let’s begin by breaking the task into two steps:

1) Gathering data after WordPress post is published.

We’ll begin with the “publish_post” hook, the hook that fires when the post is published. We’ll gather the post information to be sent to the webhooks or external API at this point.

add_action( 'publish_post', 'awp_publish_post', 10, 2 );

/**
 * Prepare data to send to webhooks on WP Post Update.
 *
 * @param  $id Post ID.
 * @param  $post Post object.
 *
 * @since 1.0.0
 */
function awp_publish_post( $id, $post ) {

	$author = $post->post_author;
	$data   = 
		array(
			'Post ID'        => $id,
			'Author Display Name' => get_the_author_meta( 'display_name', $author ),
			'Author Email Address' => get_the_author_meta( 'user_email', $author ),
			'Post Title'     => $post->post_title,
			'Post Content'   => $post->post_content,
			'Post Permalink' => get_permalink( $id ),
	);
  
  // Call the function described in step 2.
	awp_send_data_to_automate( $data );
}

2) Sending data to Webhooks or External API

Now that we’ve gathered the information to be sent upon the publishing the post. We’ll use the function awp_send_data_to_automate( $data ) called above to accomplish this task.

/**
 * Send data to webhooks.
 *
 * @param array $data posts data to send to webhooks.
 *
 * @since  1.0.0
 */
function awp_send_data_to_automate( array $data ) {

	$headers = array( 'Accept: application/json', 'Content-Type: application/json' );
	$args    = 
		array(
			'method'  => 'POST',
			'headers' => $headers,
			'body'    => wp_json_encode( $data )
	);

	$result = wp_remote_post( "your-webhook-url", $args );

	if ( is_wp_error( $result ) ) {
		error_log( print_r( $result->get_error_message(), true ) );
	}
}

That is all. The post data will be sent to the webhook when the post is published. Remember to change “your-webhook-url” to your actual webhook URL.


If you want to use a full-blown plugin instead of the code snippet, you can download the plugin Automate WP Posts from GitHub Repository, or here’s a quick download link. WIth the plugin you can simply put the Webhooks URL to Settings > Automate WP Posts, the plugin does all the rest.


Here’s the video tutorial to one of the key features listed above

Share WordPress posts in social medias such as Facebook, Twitter etc.


I hope you found this tutorial helpful. If you have any questions or confusion, let me know. I’d be happy to help!

Automate WordPress posts with Webhooks or API [code]

Sanjeev Aryal

Don't bury your thoughts, put your vision into reality ~ Bob Marley.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest