此功能利用了 WordPress 的自定义事件机制,并通过 wp_schedule_single_event() 函数实现,这有助于防止因大量收件人而引起的线程阻塞问题。
只需将以下代码段复制并粘贴到您的主题的 functions.php 文件中,即可实现该功能。
//WordPress文章更新邮件通知评论者
//https://www.daimadog.org/10379.html
function notify_commenters_on_post_update($post_id) {
$post = get_post($post_id);
$comments = get_comments(array(
'post_id' => $post_id,
'status' => 'approve',
));
if ($comments) {
foreach ($comments as $comment) {
$comment_author_email = $comment->comment_author_email;
$subject = '文章更新通知:' . $post->post_title;
$message = '亲爱的星粉,您评论过的文章《' . $post->post_title . '》已经更新,请查看最新内容。';
// 延迟发送邮件
wp_schedule_single_event(time() + 60, 'send_notification_email', array($comment_author_email, $subject, $message));
}
}
}
add_action('save_post', 'notify_commenters_on_post_update');
function send_notification_email($to, $subject, $message) {
wp_mail($to, $subject, $message);
}
为了实现定时任务,并且设置事件的执行频率,请将频率调整为60秒。