A-
A+
WordPress实现回复评论自动发送邮件给评论者,手搓插件保证安全性。
最近启用了网站的评论,但是回复别人的评论,他们收不到提醒,所以想加一个WordPress纯手搓代码实现发送,外边的插件其实很多,但我不放心。
在plugins目录下新建一个smtp.php,或者把这段代码直接放到你主题里的functions.php里也可以。
<?php
/*
Plugin Name: 自定义SMTP
Description: 不依赖插件,接管WP邮件SMTP发送
Version: 1.0
出品方:www.im2828.com
*/
add_action( 'phpmailer_init', function( $phpmailer ) {
$phpmailer->isSMTP();
// ==========这里全部改成你的服务商真实参数==========
$phpmailer->Host = 'smtp.163.com';
$phpmailer->SMTPAuth = true;
$phpmailer->Username = '你的邮箱@163.com';
$phpmailer->Password = '你的SMTP授权码,不是登录密码';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->Port = 465;
$phpmailer->From = '你的邮箱@163.com';
$phpmailer->FromName = '你的网站名字';
// 调试:开启PHPMailer内部异常抛出,方便看报错
//$phpmailer->SMTPDebug = 2;
// =================================================
});
/**
* 评论被回复时,给原评论作者发送邮件通知
*/
/**
* 评论回复通知,使用WP‑Cron异步,避免SMTP阻塞评论提交
*/
add_action( 'comment_post', function( $comment_id, $comment_approved ) {
if ( $comment_approved !== 1 ) {
return;
}
$comment = get_comment( $comment_id );
if ( empty( $comment->comment_parent ) ) {
return;
}
// 调度异步任务,延迟1秒执行,立刻返回,不阻塞评论
wp_schedule_single_event( time() + 1, 'send_reply_mail_event', array( $comment_id ) );
}, 10, 2 );
add_action( 'send_reply_mail_event', function( $comment_id ) {
$comment = get_comment( $comment_id );
if ( ! $comment ) return;
$parent_comment = get_comment( $comment->comment_parent );
if ( empty( $parent_comment->comment_author_email ) || $parent_comment->user_id > 0 ) {
return;
}
if ( strtolower( $comment->comment_author_email ) === strtolower( $parent_comment->comment_author_email ) ) {
return;
}
$post_title = get_the_title( $comment->comment_post_ID );
$post_link = get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment_id;
$to = $parent_comment->comment_author_email;
$subject = "你的评论在《{$post_title}》收到新回复";
$body = "你在文章【{$post_title}】的评论收到了回复。\n\n";
$body .= "回复人:{$comment->comment_author}\n";
$body .= "回复内容:\n{$comment->comment_content}\n\n";
$body .= "点击查看完整:{$post_link}\n";
wp_mail( $to, $subject, $body );
});
这样,然后后台启用插件,把上面中的信息改为自己的就可以了。
ality主题自带邮件发送,在inc/function/notify.php里,所以上面代码中的下面这一段就不要了
