Sending a mail when a new Post or Custom Post Type is published to your WordPress website is easy. We will use the publish_post WordPress action. Let’s see the actual code example.

PHP Snippet: Send mail in WordPress when a new Post is published

function webroom_send_mail_on_new_post( $post_id, $post  ) {
    if ( strpos($_SERVER['HTTP_REFERER'], 'edit-question') !== false ) {
        // your action or send mail goes here if the post is edited 
    } else {
			// send mail if the post is just published
			$headers = 'From: "Your Site <>' . "rn" . 'Reply-To:' . "rn" . 'X-Mailer: PHP/' . phpversion();
			$headers .= "Content-Transfer-Encoding: 8bitn";
			$headers .= "Content-Type: text/html; charset=UTF-8n";
			$headers .= 'MIME-Version: 1.0' . "rn";
			$to = '';
			$subject = 'New Post Published';
			$post_title = $post->post_title;
			$message = 'Hi, new post is published on your website: ' . $post_title;
			wp_mail($to, $subject, $message, $headers);
add_action( 'publish_post', 'webroom_send_mail_on_new_post', 10, 3 );

Paste this code snippet in your child theme’s functions.php file. Remember to change your email variables. Now every time a new post is published you’ll get notified by email.

How to send mail in WordPress when a new Custom Post Type is published

Sending mail when a new Custom Post Type is published is exactly the same as the above php snippet. We’ll just need to make 1 change in the add_action line.

For a regular Post post type the action is publish_post.

For your Custom Post type you just need to replace post with your post type. So For example if your post type is cars, the add_action will become publish_cars.

add_action( 'publish_cars', 'webroom_send_mail_on_new_post', 10, 3 );

If your post type is european_cars, the add_action will become publish_european_cars.

add_action( 'publish_european_cars', 'webroom_send_mail_on_new_post', 10, 3 );

This action can be used for any kind of php scripts, you are not limited to just sending a mail if new Post or Custom Post Type is published. For example if a post is published, you may want to update a user’s custom field with some bonus points or add a webhook to a 3rd party app.

WordPress publish_post action hook explained

publish_post is an action triggered whenever a post is updated and its new status is “publish”. Learn more here.


Leave a Reply