Wordpress, wp_mail send twice

Adham Mohamed

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');
Orlando P.

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);
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related