如何根据产品ID显示WooCommerce自定义结账账单字段
问题分析与解决方案
原代码的核心问题是仅判断购物车中第一个产品的ID,忽略了购物车存在多个产品的场景,同时未处理变量产品(变体)的父ID判断,导致无法正确触发对应字段的显示。
以下是修正后的代码,实现逻辑为:遍历购物车所有商品,检查是否存在对应字段所需的产品(含变体父产品),只要存在任意一个匹配产品,就显示对应字段:
function display_custom_checkout_fields_based_on_product( $fields ) { // 定义各字段对应的产品ID数组 $product_ids_participating_location = array( 5503 ); $product_ids_toxicology = array( 5453, 5454, 5455 ); $product_ids_artificial_intelligence = array( 5453, 5454, 5455, 5496 ); $cart_product_ids = array(); // 遍历购物车所有商品,收集产品ID(含变体父产品ID) if ( WC()->cart && ! WC()->cart->is_empty() ) { foreach ( WC()->cart->get_cart() as $cart_item ) { $product = $cart_item['data']; if ( is_a( $product, 'WC_Product' ) ) { // 如果是变体产品,获取父产品ID,否则取当前产品ID $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id(); $cart_product_ids[] = $product_id; } } } // 默认隐藏所有自定义字段 unset( $fields['billing_participating_location'] ); unset( $fields['billing_toxicology'] ); unset( $fields['billing_artificial_intelligence'] ); // 检查购物车是否存在对应产品,存在则显示字段 if ( ! empty( array_intersect( $cart_product_ids, $product_ids_participating_location ) ) ) { $fields['billing_participating_location'] = array( 'label' => 'Participating Location', 'required' => true, 'class' => array( 'form-row-wide' ), 'clear' => true, ); } if ( ! empty( array_intersect( $cart_product_ids, $product_ids_toxicology ) ) ) { $fields['billing_toxicology'] = array( 'label' => 'Toxicology', 'required' => true, 'class' => array( 'form-row-wide' ), 'clear' => true, ); } if ( ! empty( array_intersect( $cart_product_ids, $product_ids_artificial_intelligence ) ) ) { $fields['billing_artificial_intelligence'] = array( 'label' => 'Artificial Intelligence', 'required' => true, 'class' => array( 'form-row-wide' ), 'clear' => true, ); } return $fields; } add_filter( 'woocommerce_checkout_fields', 'display_custom_checkout_fields_based_on_product' );
关键改进点
- 遍历所有购物车商品,不再仅取第一个产品
- 支持变量产品:自动识别变体产品,使用父产品ID进行判断
- 使用
array_intersect检查购物车产品ID与目标ID数组是否有交集,确保只要存在匹配产品就显示对应字段 - 保留原字段的配置参数,保证字段样式和验证逻辑不变
内容的提问来源于stack exchange,提问作者WP Learner
相关产品推荐
相关产品推荐

