devofash
devofash

Reputation: 328

Sending email twice (Wordpress)

I am sending an email when a post type goes to pending.

Everything works fine but the email is sent twice.

Here's my code:

function pendingPost($id)
{
$type = get_post_type($id);
$post_user = wp_get_current_user($id);
$edit_link = get_edit_post_link($id);
$to = "[email protected]";
$subject = "New Entry needs to be approved";
    $message = "
            <html>
            <head>
            <title>Pending notification</title>
            </head>
            <body>
            <p>Hi,</p>
            <p>A new entry has been submited.</p>
            <p>Title : ".get_the_title($id)."</p>
            <p>Type : ".substr($type, 0, -1)."</p>
            <p>Author : ".$post_user->display_name."</p>
            <br />
            <p>Click <a href='".$edit_link."'>here</a> to approve it.</p>
            </body>
            </html>
            ";

    $headers = array('Content-Type: text/html; charset=UTF-8');

    $mail = wp_mail($to, $subject, $message,$headers);

}

add_action('pending_posttype', 'pendingPost', 10, 1);

Hope someone can help.

Thanks in advance.

Upvotes: 0

Views: 521

Answers (1)

Andy Tschiersch
Andy Tschiersch

Reputation: 3816

Probably the action hook pending_posttype is fired twice. With did_action() you can check if the action already was fired.

function pendingPost($id) {

    if ( did_action( 'pending_posttype' ) !== 1 ) return;

    $type = get_post_type($id);
    $post_user = wp_get_current_user($id);
    $edit_link = get_edit_post_link($id);
    $to = "[email protected]";
    $subject = "New Entry needs to be approved";
    $message = "
            <html>
            <head>
            <title>Pending notification</title>
            </head>
            <body>
            <p>Hi,</p>
            <p>A new entry has been submited.</p>
            <p>Title : ".get_the_title($id)."</p>
            <p>Type : ".substr($type, 0, -1)."</p>
            <p>Author : ".$post_user->display_name."</p>
            <br />
            <p>Click <a href='".$edit_link."'>here</a> to approve it.</p>
            </body>
            </html>
            ";

    $headers = array('Content-Type: text/html; charset=UTF-8');

    $mail = wp_mail($to, $subject, $message,$headers);

}

add_action('pending_posttype', 'pendingPost', 10, 1);

Upvotes: 1

Related Questions