Custom Comment Notifications Fire on each Page Load

I have written a custom function to notify, by email, a set of users whenever a post has a comment submitted.

The users updated vary from post to post and are defined by an array containing their user IDs.

The code works insofar that it does send out a notification email but falls over because the emails get fired multiple times (whenever a post is loaded)

Any ideas? I’m guessing comment_post is the correct hook, I just have to add a conditional in the code somewhere??

This is placed in single.php

$data = array(
‘post_id’ => $post->ID,
‘title’ => get_the_title(),
‘url’ => get_the_permalink(),
‘key_holders’ => $dhp->update_emails() // this contains the array of user IDs
);

comment_notification($data);

This is the code in my custom plugin

add_filter( ‘comment_post’, ‘comment_notification’ );

function comment_notification( $data = array()) {

if (!empty($data )) {

$id = get_comment( $comment_id );

$parent = $data[‘post_id’];
$plot = $data[‘title’];
$url = $data[‘url’];
$key_holders = $data[‘key_holders’]; // this contains the array of user IDs

$args = array(
‘number’ => ‘1’,
// ‘post_id’ => $post->ID
);

$comment = get_comments( $args );

$com_id = $comment[0]->comment_ID;
$author = $comment[0]->comment_author;
$content = $comment[0]->comment_content;
$time = $comment[0]->comment_date_gmt;

$subject = ‘Update: ‘ . $data[‘title’] . ‘ [‘ . $data[‘post_id’] . ‘/’ . $com_id . ‘]’;

$body = “<p>Hi</p>”.
“<p><b>” . ucwords($author) . “</b> has updated the Damson Home’s Portal with the following at ” . $time . “&hellip;</p>”.
wpautop($content) . “<br><p><a href=”” . $url . “#comment-” . $com_id . “”>See the full comment here.</a></p>” .
“<p>Warm regards</p>”;

$headers = array(
‘Content-Type: text/html; charset=UTF-8’
);

wp_mail( $data[‘key_holders’], $subject, $body, $headers );

} else {

echo “<h3>Oopse!!</h3>” .
“<p class=”intro”>Your comment has failed, please try again.</p>” .
“<p>Please contact us if the problem persists.</p>”;

}

}

Thanks in advance!!

Read more here:: Custom Comment Notifications Fire on each Page Load

Leave a Reply

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