评论回复邮件效果如如下:
我先来说说实现这一个功能的常规套路,这个方式需要确认你的主机支持mail函数。否则的话,是不起作用的。下面直接上代码根据自己的需要,选择一种自己需要的代码,添加在主题的
functions.php 文件的 最后一个 ?> 前面即可:
//modify by stcash.com
function comment_mail_notify($comment_id) {
$admin_email = get_bloginfo ('admin_email');
$comment = get_comment($comment_id);
$comment_author_email = trim($comment->comment_author_email);
$parent_id = $comment->comment_parent ? $comment->comment_parent : '';
$to = $parent_id ? trim(get_comment($parent_id)->comment_author_email) : '';
$spam_confirmed = $comment->comment_approved;
if (($parent_id != '') && ($spam_confirmed != 'spam') && ($to != $admin_email)) {
$wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
$subject = '您在 [' . get_option("blogname") . '] 的留言有了新回复';
$message = '
';
$from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
$headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
wp_mail( $to, $subject, $message, $headers );
}
}
add_action('comment_post', 'comment_mail_notify');
值得注意的是,刚开始增加这个函数的时候,一直报错,导致网站返回500错误而无法访问。原来是我的主题中有个文件中已经包含了这个函数。所以最好是在使用这个函数之前,使用if
(!function_exists('comment_mail_notify'))
来判断下是否本来已经存在这个函数。然而我的主机好像不支持上面的代码,应该是主机对wp_mail函数不支持。所以我换了另外一种方式来实现,主要原理是使用smtp接口来实现//使用smtp发送邮件(请根据自己使用的邮箱设置SMTP)
//使用smtp发送邮件(请根据自己使用的邮箱设置SMTP)
add_action('phpmailer_init', 'mail_smtp_2');
function mail_smtp_2( $phpmailer ) {
$phpmailer->FromName = '朱海涛自媒体'; //发件人名称
$phpmailer->Host = 'smtp.qq.com'; //修改为你使用的邮箱SMTP服务器
$phpmailer->Port = 465; //SMTP端口
$phpmailer->Username = 'stcash@stcash.com'; //邮箱账户
$phpmailer->Password = 'xz2015'; //邮箱密码
$phpmailer->From = 'stcash@stcash.com'; //邮箱账户
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPSecure = 'ssl'; //tls or ssl (port=25时->留空,465时->ssl)
$phpmailer->IsSMTP();
}
这段
代码在主机上是通用的。只需要修改发件人名称,邮箱SMTP服务器 和邮箱账户
附上各邮箱的端口及smtp地址:
188
邮箱 | pop3.188.com | smtp.188.com | 端口:25 |
163
邮箱 | pop3.163.com | smtp.163.com | 端口:25 |
126
邮箱 | pop3.126.com | smtp.126.com | 端口:25 |
netease
邮箱 | pop.netease.com | smtp.netease.com | 端口:25 |
yeah
邮箱 | pop.yeah.net | smtp.yeah.net | 端口:25 |
QQ
邮箱 | pop.qq.com | smtp.qq.com | 端口:465或587 |
嫌麻烦的站长可以直接使用后面一种方式来实现评论回复邮件提醒了。