
本文介绍如何使用 `woocommerce_email_after_order_table` 钩子,在 woocommerce 的“订单待处理”“订单处理中”和“订单已完成”三类客户邮件底部(订单表格后)精准插入针对非美国收货地址的定制化提示语。
在 WooCommerce 中,为不同地区客户定制邮件内容是提升本地化体验的重要手段。若需仅对发货国家非美国(即 shipping_country ≠ 'US') 的客户,在特定订单状态邮件(customer_on_hold_order、customer_processing_order、customer_completed_order)中追加说明性内容(例如物流时效提示、关税说明等),应避免依赖未定义变量(如原代码中的 $woocommerce),而直接通过传入的 $order 对象获取关键信息。
以下是经过验证、可直接集成到主题 functions.php 或专用插件中的标准实现:
/**
* 在指定客户邮件末尾添加非美国订单专属提示
*
* @param WC_Order $order 当前订单对象
* @param bool $sent_to_admin 是否发送给管理员(此处忽略,仅面向客户)
* @param bool $plain_text 是否为纯文本邮件格式
* @param WC_Email $email 当前邮件实例
*/
function action_woocommerce_email_after_order_table( $order, $sent_to_admin, $plain_text, $email ) {
// 限定作用范围:仅对三类客户通知生效
$target_emails = array(
'customer_on_hold_order',
'customer_processing_order',
'customer_completed_order'
);
if ( ! in_array( $email->id, $target_emails ) ) {
return;
}
// 判断是否为非美国发货地址(注意:使用 get_shipping_country(),非 billing_country)
if ( $order->get_shipping_country() !== 'US' ) {
// 支持 HTML 邮件格式;若需兼容纯文本邮件,请额外判断 $plain_text
if ( $plain_text ) {
echo "Note: This order ships outside the USA. Customs duties and delivery times may vary.\n";
} else {
echo 'Note: This order ships outside the USA. Customs duties and delivery times may vary.
';
}
}
}
add_action( 'woocommerce_email_after_order_table', 'action_woocommerce_email_after_order_table', 10, 4 );✅ 关键要点说明:
- 使用 $order->get_shipping_country() 安全获取收货国代码(返回大写 ISO 3166-1 alpha-2 格式,如 'CA'、'GB'、'AU'),无需手动 strtolower() 转换;
- 严格匹配 $email->id,避免误触发后台通知或其它客户邮件(如退款、密码重置);
- 主动区分 $plain_text 状态,确保在纯文本邮件中输出换行符 \n 而非 HTML 标签,保障可读性;
- 钩子优先级设为 10,参数数量明确为 4,符合 WooCommerce 最新版本(8.x+)规范。
⚠️ 注意事项:
- 若客户未填写收货地址(如仅填账单地址),get_shipping_country() 可能返回空值或账单国家。如业务逻辑要求强制使用账单国兜底,可改用:
$country = $order->get_shipping_country() ?: $order->get_billing_country();
- 建议将该代码封装为独立插件或使用子主题,避免主题更新时丢失;
- 修改后务必在真实非美国订单场景下测试邮件预览(推荐使用插件 WP Mail Logging 或 Email Log 辅助调试)。
通过此方案,您即可实现精准、稳定、可维护的地域化邮件内容增强,无需修改 WooCommerce 核心模板文件。










