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

WooCommerce使用Min/Max Quantities插件无法正确获取商品最大限购数量

解决方法

问题原因

WooCommerce 原生的get_max_purchase_quantity()方法默认优先返回商品库存数值,不会主动读取Min/Max Quantities插件的自定义配置,因此你拿到的始终是80的库存值。
Min/Max Quantities插件的限购配置是作为自定义字段存储在商品元数据中的,你可以直接读取对应字段值来获取配置。

代码修改方案

你可以直接替换现有代码中max_value和min_value两行的取值逻辑,修改后的完整代码如下:

add_action('woocommerce_after_shop_loop_item', 'QTY');
function QTY()
{
    global $product;
    // 读取Min/Max Quantities插件配置
    $plugin_max = get_post_meta($product->get_id(), '_min_max_quantity_max', true);
    $plugin_min = get_post_meta($product->get_id(), '_min_max_quantity_min', true);
    // 兼容处理:没有插件配置时走原生逻辑,且最大购买量不超过库存
    $max_qty = $plugin_max && $plugin_max > 0 ? min($plugin_max, $product->get_max_purchase_quantity()) : $product->get_max_purchase_quantity();
    $min_qty = $plugin_min && $plugin_min > 0 ? $plugin_min : $product->get_min_purchase_quantity();
    ?>
        <div class="shopAddToCart">
        <button  value="-" class="minus"  >-</button>
        <input 
        type="text"
        disabled="disabled"
        autocomplete="off"
        size="2"
        value="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0; ?>"
        id="count"
        data-product-id= "<?php echo $product->get_id() ?>"
        data-in-cart="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['in_cart'] : 0; ?>"
        data-in-cart-qty="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0; ?>"
        class="quantity  qty"
        max_value = "<?php echo $max_qty; ?>"
        min_value = "<?php echo $min_qty; ?>"
        >
        <button type="button" value="+" class="plus"  >+</button>
        </div>
                              <?php
}

补充说明

  • 如果你的商品是多变体类型,需要读取对应变体的元数据,将上面get_post_meta的第一个参数替换为变体ID即可
  • 代码中做了兼容处理:如果某个商品没有设置插件的限购规则,会自动沿用WooCommerce原生的库存/最小购买量逻辑,不会出现异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:24:01