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

WooCommerce商品页数量表单默认值改为最小购买量的需求

解决方案

你需要修改现有代码,通过获取商品的最小订购量元数据,来设置数量输入框的默认值。具体修改如下:

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        // 获取商品设置的最小订购量(根据B2B插件存储的元键调整,这里假设是'_min_qty')
        $min_qty = get_post_meta( $product->get_id(), '_min_qty', true );
        // 设置数量输入参数,默认值为最小订购量,无设置则用1
        $quantity_args = array(
            'input_value' => ! empty( $min_qty ) && $min_qty > 0 ? $min_qty : 1
        );
        
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
        $html .= woocommerce_quantity_input( $quantity_args, $product, false );
        $html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';
    }
    return $html;
}

关键说明:

  • 元键调整:如果上述代码中_min_qty不是你所用B2B插件存储最小订购量的元键,可以通过以下方式确认正确的键:
    1. 安装并启用自定义字段查看插件(如Advanced Custom Fields)
    2. 进入商品编辑页面,查看该商品的自定义字段,找到对应最小订购量的键名,替换代码中的_min_qty即可
  • 兼容无设置商品:代码中判断了如果没有设置最小订购量,默认值会保持为1,符合你的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:50:28