Home > database >  Sending email notification to users when their post is published in WordPress. Why Multiple times?
Sending email notification to users when their post is published in WordPress. Why Multiple times?

Time:10-19

I have a WordPress site where users can post from the front-end and the post status goes as Draft.

Now when I publish the post from Admin panel, the notification email is sent more than one time. I need to send email once.

Below my code:

if (is_admin()) {
    function notifyauthor($post_id) { 
        $post = get_post($post_id);
        $author = get_userdata($post->post_author);
        $subject = "Post publish notification";
        $headers = 'From: '.get_bloginfo( 'name' ).' <[email protected]>' . "\r\n";
        $message = "
            Hi ".$author->display_name.",
            
            Your post, \"".$post->post_title."\" has just been published.
            
            View post: ".get_permalink( $post_id )."
            
            Thank You, Admin"
            ;
            
        wp_mail($author->user_email, $subject, $message, $headers);
        }
        add_action('publish_post', 'notifyauthor');
}

I tried current_user_can('administrator') insteed to is_admin(), but same result I got.

CodePudding user response:

Many hooks will actually run more than one time. The simple solution is to add a counter by way of post_meta after the first iteration, then check it doesn't exist. This isn't tested, but should work.

function notifyauthor($post_id) {
    if (is_admin() && !(metadata_exists('post', $post_id, 'sent_notification_email'))) {
        $post = get_post($post_id);
        $author = get_userdata($post->post_author);
        $subject = "Post publish notification";
        $headers = 'From: '.get_bloginfo( 'name' ).' <[email protected]>' . "\r\n";
        $message = "
            Hi ".$author->display_name.",
            
            Your post, \"".$post->post_title."\" has just been published.
            
            View post: ".get_permalink( $post_id )."
            
            Thank You, Admin";

        wp_mail($author->user_email, $subject, $message, $headers);
        // Set a meta key as a counter
        update_post_meta($post_id, 'sent_notification_email', '1');
    }
}
add_action('publish_post', 'notifyauthor');
  • Related