Send mail to author when custom post type is saved

I have a custom post type called "documents". I can add documents (ACF repeater field) there and the users can see them in a frontend-view. Now i need to send an email-notification to the author of the post when i change the custom-post-type in the backend and save it.

In another project i worked with the following function in the functions.php file, but this code is just working when i create a new post. I don't need to send mails on creating a new post but when i save them again.

/* SEND MAIL WHEN CPT PRODUKTIONSAUFTRAG ERSTELLT */
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');

function send_emails_on_new_event($post) {
    $emails = "[email protected]";
    $headers = 'From: Name [email protected]';
    $title = wp_strip_all_tags(get_the_title($post-ID));
    $message = "New post created";
    if(get_post_type($post-ID) === 'documents') {
        wp_mail($emails, "New Post", $message, $headers);
    } 
}

Topic functions email custom-post-types Wordpress

Category Web


Try this way:

function send_emails_on_new_event( $post ) {

    $emails  = '[email protected]';
    $headers = 'From: Name <[email protected]>';
    $title   = wp_strip_all_tags( get_the_title( $post->ID ) );
    $message = 'New post created';

    if ( get_post_type( $post->ID ) === 'documents' ) {
        wp_mail( $emails, 'New Post', $message, $headers );
    }
}
add_action( 'pre_post_update', 'send_emails_on_new_event' );

From the Code Reference:

pre_post_update: Fires immediately before an existing post is updated in the database.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.