How to auto send email when publishing a custom post type?

I’d like to have an email automatically sent out to my website’s subscribers when I publish a post for a specific custom post type. I’ve found a few plugins that will do this but only for regular posts (or for any post type that gets published, not allowing you to specify a particular post type). Any suggestions would be greatly appreciated! Thanks.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Hook into transition_post_status, fetch the users and send an email to all users.

Sample code, not tested:

add_action( 'transition_post_status', 'send_mails_on_publish', 10, 3 );

function send_mails_on_publish( $new_status, $old_status, $post )
{
    if ( 'publish' !== $new_status or 'publish' === $old_status
        or 'my_custom_type' !== get_post_type( $post ) )
        return;

    $subscribers = get_users( array ( 'role' => 'subscriber' ) );
    $emails      = array ();

    foreach ( $subscribers as $subscriber )
        $emails[] = $subscriber->user_email;

    $body = sprintf( 'Hey there is a new entry!
        See <%s>',
        get_permalink( $post )
    );


    wp_mail( $emails, 'New entry!', $body );
}

You should probably use the Bcc field.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x