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

WooCommerce最小最大默认数量插件库存不足时默认值异常问题

问题解决:WooCommerce库存低于最低购买量时修改数量输入框默认值

你遇到的核心问题是原代码的条件逻辑完全颠倒,同时缺少对插件钩子优先级的处理,导致修改未生效。以下是修正方案:

原代码错误点

  • 当库存低于最低购买量时,原代码直接返回未修改的$args,完全没执行默认值替换逻辑
  • 未处理商品未设置最低购买量的边界情况
  • 钩子优先级(10)可能低于插件自身的钩子,导致你的修改被覆盖

修正后的代码

add_filter( 'woocommerce_quantity_input_args', 'adjust_quantity_input_when_low_stock', 20, 2 );

function adjust_quantity_input_when_low_stock( $args, $product ) {
    // 仅对启用库存管理的商品生效
    if ( ! $product->managing_stock() ) {
        return $args;
    }

    $stock_qty = $product->get_stock_quantity();
    $min_qty = get_post_meta( $product->get_id(), '_alg_wc_pq_minimum', true );
    $default_qty = get_post_meta( $product->get_id(), '_alg_wc_pq_default', true );

    // 跳过未设置最低购买量的商品
    if ( empty( $min_qty ) || ! is_numeric( $min_qty ) ) {
        return $args;
    }

    // 库存低于最低量时,默认值设为当前库存,同时放宽最小购买限制
    if ( $stock_qty < $min_qty ) {
        $args['input_value'] = $stock_qty;
        $args['min_value'] = 1;
    } else {
        // 库存充足时,保留插件设置的默认值(排除购物车页面)
        if ( ! empty( $default_qty ) && $default_qty != '-1' && ! is_cart() ) {
            $args['input_value'] = $default_qty;
        }
    }

    return $args;
}

关键修改说明

  1. 钩子优先级提升至20:确保你的代码能覆盖插件自身对woocommerce_quantity_input_args的修改
  2. 修正核心逻辑:当库存低于最低购买量时,主动替换input_value为当前库存数
  3. 增加边界处理:排除未启用库存管理、未设置最低购买量的商品,避免不必要的修改
  4. 同步调整最小购买限制:将min_value设为1,确保用户可以直接购买剩余库存,不会被插件的最低量规则卡住

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:22:40