Comment Email Notification for CPT Comments

I have a WordPress site where users can create new support tickets through submitting a form that posts to a Custom Post Type. I would now like WordPress to email users when there is a comment on the Custom Post (i.e. an update to the ticket).

I found this example on how to add emails to comments to CPTs. I found the answer not to be very clear or how to apply the if() conditional, and I cannot seem to get the code to work. My CPT name is jobs and I added the following code to my functions.php file:

/*
 * Email updates for Job comments
 */
if( 'jobs'==get_post_type() ) {
    add_action( 'comment_post', 'comment_email_notification', 11, 2 );
}
function comment_email_notification( $comment_ID, $commentdata ) {
$comment = get_comment( $comment_id );
$postid = $comment->comment_post_ID;
$author_email = get_post_meta( $postid, 'author_email', true);
if( isset( $author_email ) && is_email( $author_email ) ) {
    $message="New comment on <a href="" . get_permalink( $postid ) . '">' .  get_the_title( $postid ) . '</a>';
    add_filter( 'wp_mail_content_type', create_function( '', 'return "text/html";' ) );
    wp_mail( $author_email, 'New Comment', $message );
  }
}

This does not work. Normal WordPress emails do send, under the wp_mail() function.

I appreciate your help in advance!

1 Answer
1

I have figured it out. There were a bunch of issues with the existing code.

The code wasn’t getting $author_email appropriately which was causing it to fail and causing wp_mail() not to fire.

add_action('comment_post', 'comment_email_notification', 11, 2);

function comment_email_notification($comment_ID, $comment_approved) {
    $post_type = get_post_type();
    if ($post_type !== 'jobs') {
        return;
    }

    $comment = get_comment($comment_ID);
    $post_ID = $comment->comment_post_ID;
    $author_ID = get_post_field( 'post_author', $post_ID );
    $author_email = get_the_author_meta( 'user_email', $author_ID );
    if (isset($author_email) && is_email($author_email)) {
        $message="New comment on <a href="" . get_permalink($post_ID) . '">' .
            get_the_title($postid) . '</a>';

        add_filter('wp_mail_content_type',
                   create_function('', 'return "text/html";'));

        wp_mail($author_email, 'New Comment', $message);
    }
}

Leave a Comment