You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce实现移除商品B时自动移除关联商品A的技术咨询

WooCommerce商品A(ID15)与B(ID67)绑定购买解决方案

要实现商品A和B必须同时存在于购物车,缺一不可的规则,除了你已实现的“添加B自动加A”逻辑,还需要补充反向移除、添加A自动加B以及购物车状态校验的逻辑,完整代码如下:

// 辅助函数:检查购物车中是否存在指定ID的商品
function has_product_in_cart( $product_id ) {
    if ( !WC()->cart ) return false;
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( $cart_item['product_id'] === $product_id ) {
            return true;
        }
    }
    return false;
}

// 1. 添加商品时自动绑定添加对应商品
add_action( 'woocommerce_add_to_cart', function( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
    // 添加商品B(ID67)时,自动添加商品A(ID15)(避免重复添加)
    if ( $product_id === 67 && !has_product_in_cart(15) ) {
        WC()->cart->add_to_cart(15);
    }
    // 添加商品A(ID15)时,自动添加商品B(ID67)(避免重复添加)
    if ( $product_id === 15 && !has_product_in_cart(67) ) {
        WC()->cart->add_to_cart(67);
    }
}, 10, 6 );

// 2. 移除商品时自动移除绑定的对应商品
add_action( 'woocommerce_cart_item_removed', function( $cart_item_key, $cart ) {
    $removed_product_id = $cart->removed_cart_contents[ $cart_item_key ]['product_id'];
    
    // 移除商品B(ID67)时,移除商品A(ID15)
    if ( $removed_product_id === 67 && has_product_in_cart(15) ) {
        foreach ( $cart->get_cart() as $key => $item ) {
            if ( $item['product_id'] === 15 ) {
                $cart->remove_cart_item( $key );
                break;
            }
        }
    }
    
    // 移除商品A(ID15)时,移除商品B(ID67)
    if ( $removed_product_id === 15 && has_product_in_cart(67) ) {
        foreach ( $cart->get_cart() as $key => $item ) {
            if ( $item['product_id'] === 67 ) {
                $cart->remove_cart_item( $key );
                break;
            }
        }
    }
}, 10, 2 );

// 3. 购物车更新时校验绑定状态(处理手动改数量、插件修改等场景)
add_action( 'woocommerce_before_calculate_totals', function( $cart ) {
    // 避免后台重复触发或递归调用
    if ( is_admin() && !defined( 'DOING_AJAX' ) ) return;
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
    
    $has_b = has_product_in_cart(67);
    $has_a = has_product_in_cart(15);
    
    // 购物车有B但无A,自动添加A
    if ( $has_b && !$has_a ) {
        $cart->add_to_cart(15);
    }
    // 购物车有A但无B,自动添加B
    if ( $has_a && !$has_b ) {
        $cart->add_to_cart(67);
    }
}, 10, 1 );

代码说明:

  • 辅助函数:封装购物车商品检查逻辑,避免重复代码。
  • 添加商品钩子:覆盖用户添加A或B的场景,确保绑定商品自动加入且不重复。
  • 移除商品钩子:处理用户手动移除其中一个商品的情况,自动删除另一个绑定商品。
  • 购物车更新钩子:处理特殊场景(比如用户手动将商品数量改为0、第三方插件修改购物车),确保购物车始终保持A和B同时存在或同时不存在的状态。

将上述代码添加到你的主题functions.php文件或自定义插件中即可生效。

内容的提问来源于stack exchange,提问作者J. Hall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 09:35:27