Send Email on New Post Published in WordPress

Here is a short snippet that sends an email when you publish a new post on your blog. This code can also work for Custom Post Types.

add_action('future_to_publish', 'send_emails_on_new_event');
add_action('new_to_publish', 'send_emails_on_new_event');
add_action('draft_to_publish' ,'send_emails_on_new_event');
add_action('auto-draft_to_publish' ,'send_emails_on_new_event');
 
/**
 * Send emails on event publication
 *
 * @param WP_Post $post
 */
function send_emails_on_new_event($post)
{
    $emails = "[email protected], [email protected]"; //If you want to send to site administrator, use $emails = get_option('admin_email');
    $title = wp_strip_all_tags(get_the_title($post->ID));
    $url = get_permalink($post->ID);
    $message = "Link to post: n{$url}";
 
    wp_mail($emails, "New post published: {$title}", $message);
}

The result will look something like:

[Title] New post published: Your Post
    
Link to post:
http://site.co.il/your-post/

If you want to enable this for a specific Custom Post Type, add a condition inside the function like this:

...
if(get_post_type($post->ID) === 'page') //post, page, attachment or whatever other CPT you may have
{
    //use wp_mail() here!
}
...
Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!