WordPress function to send email for new and approved comments

I have written a custom WordPress function to send a user an email when a new comment is posted to there page. I thought my code sent emails only when the comment was approved. But it seems to be sending an email even when the comment is flagged by WordPress as trash.

My code:

Read More
add_action('comment_post', 'pulse_alert', 11, 2);
function pulse_alert($comment_ID, $approved) {  
    //if the comment is approved
    if ($approved) 
    {
        global $post;
        $username = $post->post_title;      
        $user = get_user_by('login', $username);

        //if the user exists
        if ($user)
        {
            //get pulse config details
            $userid = $user->ID;
            $alerts = get_cimyFieldValue($userid, 'PULSEALERT');
            $emailformat = get_cimyFieldValue($userid, 'PULSEALERTFORMAT');

            if($alerts == 'YES')
            {
                //user details
                $user_info = get_userdata($userid);
                $user_email = $user_info->user_email;

                //for page link
                $email_newpulse_pagelink = $username; 

                //for email title
                $email_newpulse_companyname = get_cimyFieldValue($userid, 'COMPANYNAME');

                //Code for Pulse alert emails
                include_once('email/email_newpulse.php');

                $headers[] = 'From: The PartnerPulse team <hello@partnerpulse.co>';
                $headers[] = 'Bcc: The PartnerPulse team <hello@partnerpulse.co>';



                //Send email
                $mail = wp_mail($user_email, $email_newpulse_subject, $email_newpulse_body, $headers);
            }
        }
    }   
}

It would seemed the $approved var is not working. Any ideas?

Related posts

Leave a Reply

2 comments

  1. I believe that $approved will be either 0/1 for unapproved/approved or “spam”

    You can see that about halfway down this page:

    http://codex.wordpress.org/Plugin_API/Action_Reference

    Your if statement is testing $approved to see if it’s true. If $approved comes through as “spam” it will equate to true as php will consider a string true unless it’s empty or “0”.

    Change your if statement to be if($approved == 1) and see how that goes.

  2. As I checked in the source, this action hook is fired just after a comment is inserted in the database. So should be in the right hook.

    But actually, the $approved var can have 3 values : 0, 1 or spam.

    So you should try like this :

    add_action('comment_post', 'pulse_alert', 11, 2);
    function pulse_alert($comment_ID, $approved) {  
        //if the comment is approved
        if ($approved == 1) 
        {
    

    You can check the function wp_allow_comment.