WordPress 評論郵件回覆,對很多人來說很重要,比如一個技術部落格,如果有人留言提問,解決了之後發個郵件提醒他,可以很好的與訪客互動溝通,使用者體驗槓槓滴。。當然,這個功能使用外掛就可以解決了。不過我們喜歡折騰。
在 functions.php 中新增以下程式碼 (原創作者 http://kan.willin.org/):
- //評論郵件回覆
- /* comment_mail_notify v1.0 by willin kan.*/
- function comment_mail_notify($comment_id) {
- $admin_email = get_bloginfo ('admin_email'); // $admin_email 可改為你指定的 e-mail.
- $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) && ($comment_author_email == $admin_email)) {
- /* 上面的判斷式, 決定傳送郵件的必要條件:
- ($parent_id != ") && ($spam_confirmed != 『spam』): 回覆的, 而且不是 spam 才可發, 必需!!
- ($to != $admin_email) : 不發給 admin.
- ($comment_author_email == $admin_email) : 只有 admin 的回覆發郵件.
- 可視個人需求修改以上條件.
- */
- //e-mail 發出點, no-reply 可改為可用的 e-mail.
- $wp_email = 'no-reply@' . preg_replace('#^www.#', '', strtolower($_SERVER['SERVER_NAME']));
- //郵件內容
- $subject = '您在 [' . get_option("blogname") . '] 的留言有了回應';
- $message = trim(get_comment($parent_id)->comment_author) . ', 您好!
- 您曾在 《' . get_the_title($comment->comment_post_ID) . '》 的留言:'
- . trim(get_comment($parent_id)->comment_content) . ' ' . trim($comment->comment_author) . ' 給您的回應:' . trim($comment->comment_content) . ' 您可以點選 ' . htmlspecialchars(get_comment_link($parent_id)) . '檢視回應完整內容 歡迎再度光臨' . get_option('home') . '' . get_option('blogname') . ' (此郵件由系統自動發出, 請勿回覆.) ';
- $from = "From: "" . get_option('blogname') . "" <$wp_email>";
- $mail_headers = "$from
Content-Type: text/html; charset=" . get_option('blog_charset') . "
"; - wp_mail( $to, $subject, $message, $headers );
- }
- }
- //發表評論時的動作鉤子
- add_action('comment_post', 'comment_mail_notify');
不過這個程式碼只對支援 mail 函式的主機有用,也就是一般 window 主機都不支援 mail 函式,如果你恰巧是 windows 主機,不要緊張,同樣先將上面的程式碼新增到 functions.php 中再說,然後再配置一個 smtp,順便說一下,不要懷疑了,當你知道你的空間是 windows 主機的話,直接去配置 smtp 吧
什麼是 SMTP? 百度百科說的很詳細了,簡單的說,比如你使用用騰訊的 SMTP 伺服器,由於 WordPress 在你的 windows 主機上不能直接發郵件給對方,那麼可以間接的,先傳送一個傳送郵件的請求到 SMTP 伺服器上,然後又 SMTP 伺服器轉發郵件。
請參考下一篇文章,SMTP 的配置