WordPress Plugin to Send Notifications to Previous Commenters

This is a simple WordPress plugin to send an e-mail to all those who previously commented on a post. When an individual posts a new comment, everyone else who previously posted a comment will receive an e-mail containing an e-mail notification that a new comment was added to a particular post. It includes some minimal logic to send the notification to everyone except the individual posting the latest comment. While not included here, I would expect this can be further expanded to include features to opt-out of receiving notifications, to turn the notifications off for particular posts, or to modify the notification message content. Add the below code to a .php file and upload it to your plugin directory. Once uploaded, activate the plugin from your dashboard and the notifications will be sent when any new comments are posted.

<?php
/*
Plugin Name: WP Notify Previous Commenters
Plugin URI: https://www.dalesandro.net/
Description: WordPress plugin to notify previous commenters of new comments.
Author: DALESANDRO.NET
Version: 1.0
Author URI: https://www.dalesandro.net/
*/

add_action('comment_post', 'email_notification');

function email_notification($comment_id) {
  $emails = array();
  $comment = get_comment($comment_id, ARRAY_A);
  $comments = get_comments('post_id=' . $comment['comment_post_ID']);

  $original_post = get_post($comment['comment_post_ID'], ARRAY_A);
  $original_poster = get_userdata($original_post['post_author']);

  foreach($comments as $this_comment) {
    array_push( $emails, $this_comment->comment_author_email);
  }
  array_push($emails, $original_poster->user_email);

  $emails = array_unique($emails);
  $emails = array_diff($emails, array($comment['comment_author_email']));

  $headers = "From: " . $comment['comment_author'] . "\r\n";
  foreach($emails as $this_email) {
    wp_mail($this_email,
            html_entity_decode(get_bloginfo('name'), ENT_QUOTES) .
             " - New Comment Notification",
             "A new comment has been added to the post \"" .
             $original_post['post_title'] .
             "\" by " . $comment['comment_author'] . ".", $headers);
  }
}
?>

Leave a Comment