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

WooCommerce产品页面追加销售商品功能故障修复请求

WooCommerce追加销售复选框缺货预订场景问题修复方案

问题根源分析

  1. “允许但通知客户”商品不显示:原代码可能仅通过is_in_stock()判断商品是否展示,忽略了WooCommerce中“允许缺货预订且通知”的商品仍属于可购买状态。
  2. “允许”缺货预订商品无法加入购物车:默认购物车添加逻辑会校验库存,自定义复选框提交的追加销售商品未触发缺货预订的特殊处理逻辑,导致库存不足时被拦截。

修复代码实现

1. 修正追加销售商品显示逻辑(解决问题1)

将原代码中判断商品是否显示的条件替换为is_purchasable(),该方法会自动识别所有可购买商品(包括无库存但允许缺货预订的所有类型):

foreach ( $upsells as $upsell ) {
    $product = wc_get_product( $upsell );
    // 仅显示可购买的商品(含所有缺货预订允许的情况)
    if ( ! $product || ! $product->is_purchasable() ) {
        continue;
    }
    // 后续商品HTML渲染代码保持不变
}

2. 修复追加销售商品购物车添加逻辑(解决问题2)

通过自定义钩子标记追加销售商品,并跳过对应库存校验,确保允许缺货预订的商品能正常加入购物车:

步骤1:添加购物车处理钩子

add_action( 'woocommerce_add_to_cart', 'custom_add_upsells_to_cart', 10, 6 );
function custom_add_upsells_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
    // 接收提交的追加销售商品数据
    if ( isset( $_POST['upsell_products'] ) && is_array( $_POST['upsell_products'] ) ) {
        foreach ( $_POST['upsell_products'] as $upsell_id => $upsell_qty ) {
            $upsell_id = absint( $upsell_id );
            $upsell_qty = absint( $upsell_qty );
            
            if ( $upsell_qty < 1 ) {
                continue;
            }
            
            $product = wc_get_product( $upsell_id );
            if ( $product && $product->is_purchasable() ) {
                // 标记该商品为允许缺货预订,用于后续跳过库存校验
                $custom_cart_data = array( 'allow_backorder' => true );
                WC()->cart->add_to_cart( $upsell_id, $upsell_qty, 0, array(), $custom_cart_data );
            }
        }
    }
}

步骤2:添加库存校验跳过钩子

add_filter( 'woocommerce_add_to_cart_validation', 'skip_upsell_backorder_stock_check', 10, 6 );
function skip_upsell_backorder_stock_check( $passed, $product_id, $quantity, $variation_id = '', $variations = '', $cart_item_data = array() ) {
    // 仅对标记为允许缺货预订的追加销售商品跳过库存校验
    if ( isset( $cart_item_data['allow_backorder'] ) && $cart_item_data['allow_backorder'] ) {
        $product = wc_get_product( $product_id );
        if ( $product && $product->backorders_allowed() ) {
            $passed = true;
        }
    }
    return $passed;
}

关键说明

  • is_purchasable()会自动处理三种缺货预订状态:不允许、允许、允许但通知,仅过滤完全不可购买的商品
  • 通过cart_item_data标记商品,避免全局跳过库存校验,保证其他商品的库存逻辑正常
  • 修复后,“允许但通知客户”的商品会正常显示,“允许”的缺货预订商品可顺利加入购物车

内容的提问来源于stack exchange,提问作者brc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:40:01