我有这个功能,可以为我发送各种电子邮件:
function tps_send_email($emailTo, $subject, $content) {
//Allow HTML in email
function tps_set_html_email_content_type() {
return \'text/html\';
}
add_filter( \'wp_mail_content_type\', \'tps_set_html_email_content_type\' );
//Send the email
$mailSent = wp_mail($emailTo, $subject, $content);
//Reset HTML content type back to text only (avoids conflicts)
remove_filter( \'wp_mail_content_type\', \'tps_set_html_email_content_type\' );
return $mailSent;
}
我使用它,这样我就不必在每次发送wp\\U邮件时手动设置内容类型。但是,如果我在另一个函数中多次使用此函数,就像这样:
function my_custom_function(){
$mailTo = \'[email protected]\';
$subject = \'Some subject line\';
$emailTemplate1 = \'template 1 content goes here\';
tps_send_email($emailTo, $subject, $emailTemplate1 );
if (some condition) {
$emailTemplate2 = \'template 2 content goes here\';
//send another email
tps_send_email($emailTo, $subject, $emailTemplate2 );
}
}
第一封邮件发送正常,但第二封邮件会抛出错误
Fatal error: Cannot redeclare tps_set_html_email_content_type()...
(这是我的
tps_send_email()
函数)。
我做错了什么?
最合适的回答,由SO网友:Milan Petrovic 整理而成
那是因为你已经把函数tps_set_html_email_content_type 内部tps_send_email, 每次你打电话,它都会宣布tps_set_html_email_content_type 再次运行。只需将其移出:
function tps_set_html_email_content_type() {
return \'text/html\';
}
function tps_send_email($emailTo, $subject, $content) {
add_filter( \'wp_mail_content_type\', \'tps_set_html_email_content_type\' );
//Send the email
$mailSent = wp_mail($emailTo, $subject, $content);
//Reset HTML content type back to text only (avoids conflicts)
remove_filter( \'wp_mail_content_type\', \'tps_set_html_email_content_type\' );
return $mailSent;
}
我不知道为什么要首先将一个函数放在另一个函数中,但这从来都不是一个好主意,即使PHP支持它。