Email notification to all thread commenters on reply in WordPress P2 theme

The following code added to the bottom of P2’s functions.php will allow P2 to send email notifications to all other responders in a comments thread.

// PluginBuddy Email Notification Patch for P2
// by Dustin Bolton on September 10, 2010.
// http://pluginbuddy.com http://site2.zirch.com
add_action( 'comment_post', 'email_notification' );
function email_notification( $comment_id ) {
	$emails = array();
	$comment = get_comment( $comment_id, ARRAY_A );
	
	// Get emails of all responders.
	$comments = get_comments( 'post_id=' . $comment['comment_post_ID'] );
	foreach( $comments as $this_comment ) {
		if ( $this_comment->comment_author_email != $comment['comment_author_email'] ) { // Only add emails that are not this comment poster.
			array_push( $emails, $this_comment->comment_author_email );
		}
	}
	
	$emails = array_unique( $emails ); // Strip all duplicate email addresses.
	
	// Get email address of thread starter to strip them from receiving replies since that is automatic in P2.
	$original_post = get_post( $comment['comment_post_ID'], ARRAY_A );
	$original_poster = get_userdata( $original_post['post_author'] );
	$emails = array_diff( $emails, array( $original_poster->user_email ) ); // Remove from array.
	
	// Send emails.
	foreach( $emails as $this_email ) {
		wp_mail( $this_email, 'P2 thread updated!', "There has been an update to a thread you posted in by " . $comment['comment_author'] . " on " . $comment['comment_date'] . ":\n\n" . $comment['comment_content'] );
	}
}
// End PluginBuddy Email Notification Patch.

Leave a Reply

Your email address will not be published. Required fields are marked *