WooCommerce结合ACF配置新订单邮件按所属机构BCC发送问题
问题描述
- 需要按地理位置将平台客户归属到对应代理网点(Agency),每个网点配置独立管理账号,新订单通知邮件需自动发送至下单客户所属的对应网点
- 已通过ACF插件为客户账号创建选择所属网点的单选按钮字段,需实现订单邮件密送(BCC)到对应网点邮箱,但现有代码无法正确获取客户所属网点字段值,也无法匹配对应网点邮箱触发BCC发送
原有代码
ACF字段注册代码
if( function_exists('acf_add_local_field_group') ): acf_add_local_field_group(array( 'key' => 'group_62b97460daadb', 'title' => 'Agence Barrault / AutoFit', 'fields' => array( array( 'key' => 'field_62b9746e368c2', 'label' => 'Sélectionner une Agence', 'name' => 'agence', 'type' => 'radio', 'instructions' => '', 'required' => 1, 'conditional_logic' => 0, 'wrapper' => array( 'width' => '', 'class' => '', 'id' => '', ), 'choices' => array( 1 => 'Test', 2 => 'La Rochelle', 3 => 'Saintes', 4 => 'Rochefort', ), 'allow_null' => 0, 'other_choice' => 0, 'default_value' => 1, 'layout' => 'vertical', 'return_format' => 'value', 'save_other_choice' => 0, ), ), 'location' => array( array( array( 'param' => 'user_form', 'operator' => '==', 'value' => 'all', ), ), ), 'menu_order' => 0, 'position' => 'normal', 'style' => 'default', 'label_placement' => 'top', 'instruction_placement' => 'label', 'hide_on_screen' => '', 'active' => true, 'description' => '', 'show_in_rest' => 0, )); endif;
原有功能实现代码
add_filter( 'woocommerce_email_headers', 'bcc_to_email_headers', 10, 3 ); function bcc_to_email_headers( $headers, $email_id, $order ) { if ( $email_id === 'new_order' ) { $value = get_field( 'field_62b9746e368c2', 'agence' ); if ( $value == [1] ) { $headers .= "Bcc: Name <exemple@email.com> \r\n"; } } return $headers; }
原有代码问题说明
get_field调用参数错误:该ACF字段是绑定在用户对象上的,第二个参数需要传入对应用户ID,不能直接传字符串agence,否则无法获取到正确值- 判断逻辑错误:单选按钮字段的返回值是单个数字/字符串,不是数组,不能和数组
[1]做比对 - 缺少网点ID与对应邮箱的映射关系,无法批量匹配所有网点的发送规则
修复后实现代码
add_filter( 'woocommerce_email_headers', 'bcc_to_agency_email', 10, 3 ); function bcc_to_agency_email( $headers, $email_id, $order ) { // 仅针对新订单通知邮件生效 if ( $email_id !== 'new_order' || ! is_a( $order, 'WC_Order' ) ) { return $headers; } // 配置网点ID和对应邮箱、名称的映射,按需替换为实际信息 $agency_email_map = array( 1 => array( 'name' => 'Test', 'email' => 'test@exemple.com' ), 2 => array( 'name' => 'La Rochelle', 'email' => 'larochelle@exemple.com' ), 3 => array( 'name' => 'Saintes', 'email' => 'saintes@exemple.com' ), 4 => array( 'name' => 'Rochefort', 'email' => 'rochefort@exemple.com' ) ); // 获取下单用户ID $customer_id = $order->get_customer_id(); if ( ! $customer_id ) { return $headers; } // 获取用户所属网点ID $agency_id = get_field( 'agence', 'user_' . $customer_id ); // 网点存在对应邮箱配置则添加BCC头 if ( $agency_id && isset( $agency_email_map[ $agency_id ] ) ) { $agency = $agency_email_map[ $agency_id ]; $headers .= "Bcc: {$agency['name']} <{$agency['email']}> \r\n"; } return $headers; }
使用说明
- 将代码中
$agency_email_map数组内的邮箱替换为各网点实际使用的邮箱 - 后续新增网点时,只需在
$agency_email_map中添加对应ID、名称、邮箱的键值对即可,无需修改其他逻辑 - 代码放入当前主题的
functions.php文件或者自定义功能插件中即可生效
内容的提问来源于stack exchange,提问作者Guillaume Arnault
相关产品推荐
相关产品推荐

