WooCommerce自定义结账字段如何在客户保留订单邮件中显示?
解决WooCommerce自定义字段不显示在客户邮件的问题
嘿,我来帮你搞定这个问题!你说的没错,WooCommerce确实没有直接的$sent_to_customer变量,但我们可以通过邮件对象的属性来判断是不是发给客户的邮件,轻松把自定义字段加到客户的保留订单邮件里。
核心思路
管理员邮件能显示,说明你已经正确保存了自定义字段,只是添加邮件内容的代码可能只限制了管理员可见。我们只需要调整判断条件,让内容也在客户邮件里输出就行。
具体解决方案
假设你原来的代码是类似这样(只在管理员邮件显示):
add_action('woocommerce_email_order_details', 'add_custom_field_to_admin_email', 10, 4); function add_custom_field_to_admin_email($order, $sent_to_admin, $plain_text, $email) { if ($sent_to_admin) { $custom_value = get_post_meta($order->get_id(), '你的自定义字段key', true); if (!empty($custom_value)) { echo '<p><strong>自定义字段名称:</strong> ' . esc_html($custom_value) . '</p>'; } } }
你可以用下面两种方式修改:
方式一:让自定义字段在所有邮件(管理员+客户)中显示
直接去掉$sent_to_admin的判断,同时适配纯文本和HTML邮件格式:
add_action('woocommerce_email_order_details', 'add_custom_field_to_all_emails', 10, 4); function add_custom_field_to_all_emails($order, $sent_to_admin, $plain_text, $email) { // 替换成你实际的自定义字段key $custom_field_key = '你的自定义字段key'; $custom_value = get_post_meta($order->get_id(), $custom_field_key, true); if (!empty($custom_value)) { if ($plain_text) { // 纯文本邮件格式 echo '自定义字段名称: ' . esc_html($custom_value) . "\n"; } else { // HTML邮件格式 echo '<p><strong>自定义字段名称:</strong> ' . esc_html($custom_value) . '</p>'; } } }
方式二:仅在客户邮件中显示(精准控制)
如果你只想让客户看到,不想在管理员邮件重复显示,可以用$email->is_customer_email()方法判断,或者指定具体的客户邮件ID(比如保留订单邮件的ID是customer_on_hold_order):
add_action('woocommerce_email_order_details', 'add_custom_field_to_customer_emails', 10, 4); function add_custom_field_to_customer_emails($order, $sent_to_admin, $plain_text, $email) { // 方式A:判断是否是客户邮件 if ($email->is_customer_email()) { $custom_value = get_post_meta($order->get_id(), '你的自定义字段key', true); if (!empty($custom_value)) { if ($plain_text) { echo '自定义字段名称: ' . esc_html($custom_value) . "\n"; } else { echo '<p><strong>自定义字段名称:</strong> ' . esc_html($custom_value) . '</p>'; } } } // 方式B:指定仅在保留订单邮件显示 // if ($email->id === 'customer_on_hold_order') { // // 同上的字段输出代码 // } }
关键注意点
- 替换代码中的
你的自定义字段key为你实际使用的字段键名; - 如果你用的是其他邮件钩子(比如
woocommerce_email_after_order_table),逻辑完全一样,只需要替换钩子名称即可; - 测试时可以手动触发保留订单邮件,或者用WooCommerce的邮件测试工具验证效果。
内容的提问来源于stack exchange,提问作者Brett
相关产品推荐
相关产品推荐

