如何将WC Fields Factory的student_email设为WooCommerce邮件收件人
Got it, let's get this sorted. You've already got the student_email field working via WC Fields Factory (and it's showing up in carts/order confirmations—nice work). Now we just need to hook into WooCommerce's email system to redirect or add that student email as the recipient for your target emails.
核心思路
WooCommerce uses filter hooks for every email's recipient list. We'll grab the student_email value stored in the order metadata (WC Fields Factory saves these with a wccaf_ prefix by default) and override/add it to the recipient list.
代码实现
Add this to your active theme's functions.php file (or a custom plugin—never edit core WooCommerce files!):
// 修改新订单邮件的收件人为学生邮箱 add_filter( 'woocommerce_email_recipient_new_order', 'set_student_email_as_recipient', 10, 2 ); function set_student_email_as_recipient( $original_recipient, $order ) { // 确保我们拿到的是有效的订单对象 if ( ! is_a( $order, 'WC_Order' ) ) { return $original_recipient; } // 从订单元数据中获取学生邮箱(WC Fields Factory默认前缀是wccaf_) $student_email = $order->get_meta( 'wccaf_student_email' ); // 验证邮箱有效,再替换收件人 if ( ! empty( $student_email ) && is_email( $student_email ) ) { // 替换为学生邮箱(如果要保留原收件人,比如管理员也收到,用下面一行) // $original_recipient = $original_recipient . ',' . $student_email; $original_recipient = $student_email; } return $original_recipient; }
关键细节调整
针对不同邮件模板:
- 如果要修改客户的订单处理中邮件,把钩子改成
woocommerce_email_recipient_customer_processing_order - 如果是客户完成订单邮件,用
woocommerce_email_recipient_customer_completed_order - WooCommerce的所有邮件钩子都遵循
woocommerce_email_recipient_{email_id}格式,你可以在邮件设置里找到对应的ID。
- 如果要修改客户的订单处理中邮件,把钩子改成
确认订单元数据键:
- 不确定
wccaf_student_email是不是正确的键?去WooCommerce后台打开一个测试订单,找到「订单元数据」区域,查看你的学生邮箱字段对应的元键(通常WC Fields Factory会自动加wccaf_前缀),替换代码里的键名即可。
- 不确定
同时发送给多人:
- 如果你想让商店管理员和学生都收到邮件,注释掉替换的行,启用那行用逗号拼接的代码即可。
测试建议
- 下一个测试订单,填写有效的学生邮箱,检查邮件是否发送到正确的地址。
- 确保你的
student_email字段在WC Fields Factory里设置为必填,避免出现空邮箱的情况。
内容的提问来源于stack exchange,提问作者calwex718

