Email Commenters When Someone Replies (Opt-In)
Adds a "Notify me of replies" checkbox to the comment form and emails the commenter once a reply to their comment is approved.
Opens WPIDE on
Code
$wpide_reply_checkbox = function () {
echo '<p class="comment-form-wpide-notify"><label><input type="checkbox" name="wpide_notify_replies" value="1"> Email me when someone replies to my comment</label></p>';
};
add_action( 'comment_form_after_fields', $wpide_reply_checkbox );
add_action( 'comment_form_logged_in_after', $wpide_reply_checkbox );
$wpide_notify_parent = function ( $comment ) {
$comment = get_comment( $comment );
if ( ! $comment || ! $comment->comment_parent || '1' !== (string) $comment->comment_approved || get_comment_meta( $comment->comment_ID, 'wpide_reply_notified', true ) ) {
return;
}
$parent = get_comment( $comment->comment_parent );
if ( ! $parent || ! get_comment_meta( $parent->comment_ID, 'wpide_notify_replies', true ) || ! is_email( $parent->comment_author_email ) || $parent->comment_author_email === $comment->comment_author_email ) {
return;
}
update_comment_meta( $comment->comment_ID, 'wpide_reply_notified', 1 );
wp_mail(
$parent->comment_author_email,
sprintf( 'New reply to your comment on "%s"', wp_specialchars_decode( get_the_title( $comment->comment_post_ID ), ENT_QUOTES ) ),
sprintf(
"Hi %s,\n\n%s replied to your comment:\n\n%s\n\nRead the conversation: %s",
$parent->comment_author,
$comment->comment_author,
wp_trim_words( wp_strip_all_tags( $comment->comment_content ), 60 ),
get_comment_link( $comment )
)
);
};
add_action( 'comment_post', function ( $comment_id, $approved ) use ( $wpide_notify_parent ) {
if ( ! empty( $_POST['wpide_notify_replies'] ) ) {
add_comment_meta( $comment_id, 'wpide_notify_replies', 1, true );
}
if ( 1 === $approved ) {
$wpide_notify_parent( $comment_id );
}
}, 10, 2 );
add_action( 'transition_comment_status', function ( $new_status, $old_status, $comment ) use ( $wpide_notify_parent ) {
if ( 'approved' === $new_status && 'approved' !== $old_status ) {
$wpide_notify_parent( $comment );
}
}, 10, 3 );
Notes
Each reply sends at most one email, and replies by the original commenter are skipped.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.