WordPress 評論郵件回覆,對很多人來說很重要,比如一個技術部落格,如果有人留言提問,解決了之後發個郵件提醒他,可以很好的與訪客互動溝通,使用者體驗槓槓滴。。當然,這個功能使用外掛就可以解決了。不過我們喜歡折騰。

在 functions.php 中新增以下程式碼 (原創作者 http://kan.willin.org/):

  1. //評論郵件回覆   
  2. /* comment_mail_notify v1.0 by willin kan.*/     
  3. function comment_mail_notify($comment_id) {     
  4.     $admin_email = get_bloginfo ('admin_email'); // $admin_email 可改為你指定的 e-mail.      
  5.     $comment = get_comment($comment_id);      
  6.     $comment_author_email = trim($comment->comment_author_email);      
  7.     $parent_id = $comment->comment_parent ? $comment->comment_parent : '';      
  8.     $to = $parent_id ? trim(get_comment($parent_id)->comment_author_email) : '';      
  9.     $spam_confirmed = $comment->comment_approved;      
  10.     if (($parent_id != '') && ($spam_confirmed != 'spam') && ($to != $admin_email) && ($comment_author_email == $admin_email)) {   
  11.        
  12.     /* 上面的判斷式, 決定傳送郵件的必要條件:  
  13.     ($parent_id != ") && ($spam_confirmed != 『spam』): 回覆的, 而且不是 spam 才可發, 必需!!    
  14.     ($to != $admin_email) : 不發給 admin.    
  15.     ($comment_author_email == $admin_email) : 只有 admin 的回覆發郵件.    
  16.     可視個人需求修改以上條件.    
  17.     */  
  18.     //e-mail 發出點, no-reply 可改為可用的 e-mail.    
  19.     $wp_email = 'no-reply@' . preg_replace('#^www.#', ''strtolower($_SERVER['SERVER_NAME']));   
  20.     //郵件內容    
  21.     $subject = '您在 [' . get_option("blogname") . '] 的留言有了回應';   
  22.     $message =  trim(get_comment($parent_id)->comment_author) . ', 您好!  
  23.         您曾在 《' . get_the_title($comment->comment_post_ID) . '》 的留言:'  
  24.         . 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') . '  (此郵件由系統自動發出, 請勿回覆.) ';  
  25.         $from = "From: "" . get_option('blogname') . "" <$wp_email>";   
  26.         $mail_headers = "$from
    Content-Type: text/html; charset="
     . get_option('blog_charset') . "
    "
    ;   
  27.         wp_mail( $to$subject$message$headers );   
  28.     }      
  29. }   
  30. //發表評論時的動作鉤子      
  31. add_action('comment_post', 'comment_mail_notify');  

不過這個程式碼只對支援 mail 函式的主機有用,也就是一般 window 主機都不支援 mail 函式,如果你恰巧是 windows 主機,不要緊張,同樣先將上面的程式碼新增到 functions.php 中再說,然後再配置一個 smtp,順便說一下,不要懷疑了,當你知道你的空間是 windows 主機的話,直接去配置 smtp 吧

什麼是 SMTP? 百度百科說的很詳細了,簡單的說,比如你使用用騰訊的 SMTP 伺服器,由於 WordPress 在你的 windows 主機上不能直接發郵件給對方,那麼可以間接的,先傳送一個傳送郵件的請求到 SMTP 伺服器上,然後又 SMTP 伺服器轉發郵件。

請參考下一篇文章,SMTP 的配置