我编写了一个自定义函数,每当一篇文章提交了评论时,通过电子邮件通知一组用户。
更新的用户因帖子而异,并由一个数组定义,该数组包含用户ID生成的电子邮件地址。
该代码的工作原理是,它确实发送了一封通知电子邮件,但由于电子邮件被多次激发(每当加载帖子时),它就失败了
有什么想法吗?我猜是吧comment_post
是正确的钩子,我只需要在代码的某个地方添加一个条件??
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 email addresses
);
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 email addresses
$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 . "…</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>";
}
}
提前谢谢!!
更新(格式更好的@swissspidy answer版本)
add_filter( \'comment_post\', \'comment_notification\', 20, 3 );
function comment_notification( $comment_ID, $comment_approved, $commentdata) {
$postid = $commentdata[\'comment_post_ID\']; // this is how you get the post ID
// Stuff
}