Home / WordPress / Send email when new comment is posted in WordPress

Send email when new comment is posted in WordPress

Published On: March 18th, 2020|Categories: WordPress|Tags: |2 min read|

In this article you’ll learn how to create custom email notification when new comment is posted in WordPress. By default you can set only the administrator to be notified via email when Anyone posts a comment or A comment is held for moderation. This can be set in Settings -> Discussion -> Email me whenever.

How to Send custom email when new comment is posted

To send your custom email to whoever you want copy and paste the following code in your child theme’s functions.php file. You see on line 2 we’re checking if the comment is approved and published. Only then we send out the email. Remember to change the $msg, $subject and $headers variables with your content.

function send_email_to_commenter_autoresponder( $comment_ID, $comment_approved ) {
    if( 1 === $comment_approved ){
      
		// Retrieve the email of the author of the current comment.
		$comment_author_email = get_comment_author_email( $comment_ID );
      
      	// get post id of the comment
		$comment = get_comment( $comment_ID );
		$postid = $comment->comment_post_ID;
		
      	// the subject of the email
        $subject = 'Your notification subject';
      
		// the message
		$msg = 'New comment on <a href="' . get_permalink( $postid ) . '">' .  get_the_title( $postid ) . '</a> by' . $comment_author_email;
		
      	// the headers of the email
		$headers = 'From: <your-email@example.com>' . "\r\n" . 'Reply-To: your-email@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
		
		mail($comment_author_email,$subject,$msg,$headers);
    }
}
add_action( 'comment_post', 'send_email_to_commenter_autoresponder', 10, 2 );

The hook we used comment_post is fired immediately after a comment is inserted into the database. So after the comment is in the database, we check if it is approved and then we send out the email.

Use cases

  • to send custom notification to email different than the administrator;
  • you can send the commenter custom email/notification regarding his comment;
  • as autoresponder for new comments;
  • to thank the commenter;
  • what else? Share in the comments section below.



Related Articles

If you enjoyed reading this, then please explore our other articles below:

More Articles

If you enjoyed reading this, then please explore our other articles below: