WordPress有着非常方便易用的邮件通知功能,但默认却无法设置多个管理员信箱,如果我们希望系统在发出通知邮件 (如新用户注册、回复留言等) 时,能同时寄给多个管理员时,是否有办法做到?
在我们外挂邮件(Plugin)或主题functions.php时,如果有发送邮件的需求时,我们会使用wp_mail这个函式来处理:
// $to参数要指定一个寄送的E-mail地址,其后参数依序为邮件主题、内容、标题、附件 wp_mail( $to, $subject, $message, $headers, $attachments ); |
因为之前工作急用,需要实现此功能,当下觉得hack一点点wp_mail的代码会是最快的作法XD,希望知道正规作法的朋友可以提供其他说明。
好的,hack的概念很简单,因为默认的wp_mail的第一个参数,只能处理一个E-mail地址,所以稍稍加一点code进去,同时也确保让外头使用wp_mail的程式不受影响。首先请打开 wp-includes/pluggable.php 寻找大约 270行左右,会发现 wp_mail 函数完整的代码:
function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) { // Compact the input, apply the filters, and extract them back out extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) ); /* / ...........这里略过很多行,直接到最后............../ */ // Send! $result = @$phpmailer->Send(); return $result; } |
我们只要把第一个参数视为「很多E-mail地址」的组合,再用一个括号把所有的内容包起来,就大功告成了:
// 第一个参数改名了 function wp_mail( $targets, $subject, $message, $headers = '', $attachments = array() ) { // 把第一个参数用","切成数组,表示E-mail是用","来区隔 $tars = explode(",", $targets); // 用foreach,针对每组E-mail,都做一次原本wp_mail会做的事 foreach($tars as $to) { // Compact the input, apply the filters, and extract them back out extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) ); /* / ...........这里略过很多行,直接到最后............../ */ // Send! $result = @$phpmailer->Send(); } // foreach的结尾,记得放在return前 return $result; } |
修改完成了,现在到WP后台的「设置/常规」里面的电子邮件信箱,只要以,区隔每个邮箱,例如:[email protected],test2test.com 就能设定多个E-mail邮箱。
参考资料:
wp_mail的官方codex说明