Adham Mohamed
Adham Mohamed

Reputation: 5

Wordpress, wp_mail send twice

i'm using this snippet to send email to users when their post deleted, it working but sending the same mail twice, any help please

function authorNotification($post_id) {
global $wpdb;
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$message = "
Hi ".$author->display_name.",
We are sorry to inform you that your article, ".$post->post_title." has been declined. We strongly recommend you to go through the guest posting guidelines before you submit an article again.
";
wp_mail($author->user_email, "Declined", $message);
}
add_action('delete_post', 'authorNotification');

Upvotes: 0

Views: 2186

Answers (3)

Sebastián Rossi
Sebastián Rossi

Reputation: 41

Because you need to kill the process after sending mail.

Just add die(); after the wp function

wp_mail($author->user_email, "Declined", $message);
die();

Upvotes: 3

Orlando P.
Orlando P.

Reputation: 631

The function you hook into delete_post executes as many times as needed.

When you delete a post you also delete all of its revisions therefore the function will be executed more than once if the post has revisions and depending how many it had.

In order to avoid having your function execute each time WordPress deletes posts from the database you can use did_action( $hook ).

This function returns the number of times the hook executed. We can use this to fix the multiple-executions problem by placing and if statement.

function authorNotification($post_id) {

    global $wpdb;

    $post = get_post($post_id);

    $author = get_userdata($post->post_author);

    $message = "Hi ".$author->display_name.", We are sorry to inform you that your article, ".$post->post_title." has been declined. We strongly recommend you to go through the guest posting guidelines before you submit an article again.";

    if (did_action('delete_post') === 1){
        //only send once
        wp_mail($author->user_email, "Declined", $message);
    }
}

Upvotes: 2

spoofie
spoofie

Reputation: 125

Can't really tell whats going wrong here. function seems to work properly.

i suspect you are calling the function authorNotification() twice somewhere within your code, maybe delete_post is called twice?

Upvotes: 0

Related Questions