让代码更简单

WordPress文章更新邮件通知评论者

重要:本文最后更新于2024-02-27 12:22:39,某些文章具有时效性,若有错误或已失效,请在下方留言或联系代码狗

这个功能使用到wordpress的自定义事件功能,通过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,单位是秒。

感觉很棒!可以赞赏支持我哟~

0 打赏

评论 (0)

登录后评论
QQ咨询 邮件咨询 狗哥推荐