Notify WordPress users of newly published post

So you have a post section and each time you publish a new custom post you’d like to notify all your users (subscriber). It could be a post, a product, an event or perhaps a tutorial etc.

Usually the action hook would be ‘publish_post’ or ‘publish_page’ but those hooks only work for Posts and Pages.

The following example shows how this can be done to notify users that a Deputy Head has submitted a lesson for review:

<?php
function notify_users($post_ID)  {
	// a conditional to check that this is a new post
	if( ( $_POST['post_status'] == 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) ) {
		// get all users email addresses
		$wp_user_search = new WP_User_Query( array( 'fields' => array('user_email') ) );
		$usersarray = $wp_user_search->get_results();
		$arrUsers = array();
		// store each email for later use
		for ($arr = $usersarray, $allU = count($arr), $key = 0; $key < $allU; $key++) {
			$arrUsers[] = $arr[$key]->user_email;
		}
		// create the from details 
		$headers[] = 'From: Site Admin<admin@example.net>';
		// lets cc in the head just because we can 
		$headers[] = 'Cc: Site Support <support@example.net>';
		// separate the users array
		$users = implode(",", $arrUsers);
		// concatenate a message together
		$message = 'A new post has been opened for your review on the site ' . get_bloginfo('siteurl') . "\r\n\r\n";
		$message .= 'You can review it now at ' . get_permalink($post_ID) . "\r\n\r\n";
		$message .= 'Feel free to leave a comment and any suggestions.' . "\r\n\r\n";
		$message .= 'Praveen Shekhawat.';
		// and finally send the email
		wp_mail($users, "Blog Title: "  . $_POST['post_title'] , $message, $headers );
	    return $post_ID;
    }
}
// hook on to the custom post type by using 'publish_lesson'
add_action('publish_post', 'notify_users');
?>

These hooks will not work with custom post types! So, what about custom post types?

Please use bellow hook for custom post types.

<?php
/* a custom post type called ‘event’ you can now use ‘publish_event’ to hook your function */
add_action('publish_event', 'notify_users');
?>

It’s really is as simple as that.

Leave a Reply

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