求助:替换WooCommerce默认客户完成订单邮件代码未生效
替换WooCommerce客户完成订单邮件模板的问题排查与修复
问题描述
开发插件时尝试用插件内的自定义模板替换WooCommerce默认的客户完成订单邮件,但当前代码未生效,仍调用默认模板。
现有代码
构造函数
define( 'BKF_WC_EMAIL_PATH', plugin_dir_path( __FILE__ ) ); add_filter('wc_get_template', array($this, 'bkf_customer_completed_order_template'), PHP_INT_MAX, 5);
替换函数
function bkf_customer_completed_order_template($template, $template_name, $args, $template_path, $default_path) { if( $template_name == 'emails/customer-completed-order.php' ) { $template = trailingslashit(BKF_WC_EMAIL_PATH) . 'templates/' . $template_name; return $template; } }
问题排查与修复方案
1. 修复函数返回值逻辑
原函数仅在匹配模板时返回新路径,不匹配场景下无返回值,会导致wc_get_template过滤器返回null,既可能引发错误,也会干扰WooCommerce的模板判断逻辑。必须确保函数始终返回模板路径:
function bkf_customer_completed_order_template($template, $template_name, $args, $template_path, $default_path) { if( $template_name == 'emails/customer-completed-order.php' ) { $custom_template = trailingslashit(BKF_WC_EMAIL_PATH) . 'templates/' . $template_name; // 先检查自定义模板是否存在,避免加载不存在的文件引发错误 if (file_exists($custom_template)) { $template = $custom_template; } } // 无论是否匹配,都返回模板路径 return $template; }
2. 验证模板文件路径与存在性
- 确认插件内的模板文件路径为:
插件根目录/templates/emails/customer-completed-order.php - 可临时添加调试代码,输出路径并验证文件是否存在(修复完成后可删除):
// 调试用代码 error_log('自定义模板路径:' . $custom_template); error_log('模板是否存在:' . (file_exists($custom_template) ? '是' : '否'));
3. 改用WooCommerce邮件专属过滤器
wc_get_template是通用模板过滤器,对于邮件模板,WooCommerce提供了更精准的woocommerce_email_template过滤器,可替换构造函数中的钩子:
// 替换原构造函数中的add_filter代码 add_filter('woocommerce_email_template', array($this, 'bkf_customer_completed_order_template'), PHP_INT_MAX, 5);
4. 直接修改邮件类的模板路径
另一种更可靠的方式是通过woocommerce_email_classes过滤器,直接修改对应邮件类的模板根路径:
// 在构造函数中添加此钩子 add_filter('woocommerce_email_classes', array($this, 'bkf_replace_completed_order_email_class')); function bkf_replace_completed_order_email_class($email_classes) { if (isset($email_classes['WC_Email_Customer_Completed_Order'])) { // 设置自定义模板的根目录 $email_classes['WC_Email_Customer_Completed_Order']->template_base = trailingslashit(BKF_WC_EMAIL_PATH) . 'templates/'; // 若自定义模板文件名与默认不同,可修改此行 // $email_classes['WC_Email_Customer_Completed_Order']->template_name = '自定义模板文件名.php'; } return $email_classes; }
内容的提问来源于stack exchange,提问作者Scott L
相关产品推荐
相关产品推荐

