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

WooCommerce批发用户角色设置最小订单量10件的PHP问题

WooCommerce批发用户购物车最低数量限制问题修复

问题描述

需要实现WooCommerce批发用户(wholesale角色)购物车商品总量满10件才能进入结算页,未达标时隐藏「前往结算」按钮及GPay、Apple Pay等Stripe支付按钮。当前代码在首次进入、刷新购物车页时有效,但更新购物车数量后按钮会重新显示,使用代码片段插件管理代码(未使用子主题),尝试多个同类PHP片段后问题仍未解决。

现有代码:

// Set a minimum quantity for wholesale role
add_action( 'woocommerce_before_cart', 'thumbtoe_minimum_order_quantity' ); // Error message on cart page
add_action( 'woocommerce_check_cart_items', 'thumbtoe_minimum_order_quantity' );
add_action( 'woocommerce_proceed_to_checkout', 'thumbtoe_minimum_order_quantity' ); // Error message on cart page

function thumbtoe_minimum_order_quantity() {
    // Set the minimum quantity
    $minimum_quantity = 10;
    // Get the current user
    $user = wp_get_current_user();

    // Check if the user has the wholesale role
    if ( in_array( 'wholesale', (array) $user->roles ) ) {
        // Get total quantity in cart
        $total_quantity = WC()->cart->get_cart_contents_count();

        // If total quantity is less than minimum
        if ( $total_quantity < $minimum_quantity ) {
            // Error message
            $error_message = sprintf( 'Retail Partners Minimum order amount must exceed %s items in your cart to proceed.', $minimum_quantity );

            // Display the error message on the cart page
            wc_print_notice( $error_message, 'error' );

            // Remove the Proceed to Checkout button
            add_action( 'wp_footer', function() {
                ?>
                <script type="text/javascript">
                    jQuery(function($) {
                        $('a.checkout-button').remove(); // Remove the Proceed to Checkout button
                        $('.gpay-card-info-container-fill').hide(); // Hide GPay button
                        $('.apple-pay-button').hide(); // Hide Apple Pay button
                        $('.wc-stripe-cart-checkout-container ul.wc_stripe_cart_payment_methods.active li.wc-stripe-payment-method, p').remove(); // Remove specified Stripe elements
                    });
                </script>
                <?php
            });

            return; // Stop further execution
        }
    }
}

问题原因

购物车数量更新是AJAX异步操作,原代码仅在页面初始加载时执行JS隐藏逻辑;AJAX更新后购物车区域会重新渲染,被移除的按钮会被重新生成,且原JS未监听AJAX完成事件,导致按钮再次显示。

解决方案

通过监听WooCommerce购物车AJAX更新事件,结合CSS持久隐藏+动态JS控制,确保数量变化后验证逻辑实时生效:

// 设置批发用户最低下单数量
add_action( 'woocommerce_before_cart', 'wholesale_min_order_quantity_check' );
add_action( 'woocommerce_check_cart_items', 'wholesale_min_order_quantity_check' );
add_action( 'woocommerce_cart_updated', 'wholesale_min_order_quantity_check' ); // 监听AJAX购物车更新

function wholesale_min_order_quantity_check() {
    $minimum_qty = 10;
    $user = wp_get_current_user();

    // 仅针对wholesale角色用户
    if ( !in_array( 'wholesale', (array)$user->roles ) ) return;

    $total_qty = WC()->cart->get_cart_contents_count();
    $is_under_min = $total_qty < $minimum_qty;

    // 注册全局变量供JS使用
    wp_localize_script( 'jquery', 'wholesaleCartData', array(
        'isUnderMin' => $is_under_min,
        'minQty'     => $minimum_qty
    ) );

    if ( $is_under_min ) {
        $error_msg = sprintf( '批发用户需满 %s 件商品才能结算,请继续添加商品。', $minimum_qty );
        wc_print_notice( $error_msg, 'error' );
        
        // 添加CSS类控制隐藏,比JS remove更稳定
        add_action( 'wp_head', function() {
            ?>
            <style>
                .checkout-button, .gpay-card-info-container-fill, .apple-pay-button, 
                .wc-stripe-cart-checkout-container ul.wc_stripe_cart_payment_methods.active li.wc-stripe-payment-method {
                    display: none !important;
                }
            </style>
            <?php
        } );
    }
}

// 监听购物车AJAX更新事件,重新执行验证逻辑
add_action( 'wp_footer', 'wholesale_cart_ajax_listener' );
function wholesale_cart_ajax_listener() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            // 初始加载时检查
            toggleCheckoutButtons(wholesaleCartData.isUnderMin);

            // 监听WooCommerce购物车更新AJAX事件
            $(document).on('updated_cart_totals', function() {
                // AJAX更新后重新获取购物车数量并检查
                $.ajax({
                    url: wc_cart_params.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'get_wholesale_cart_qty'
                    },
                    success: function(response) {
                        const isUnderMin = parseInt(response) < wholesaleCartData.minQty;
                        toggleCheckoutButtons(isUnderMin);
                        
                        // 如果未达标,重新显示错误提示
                        if (isUnderMin && $('.woocommerce-error:contains("批发用户需满")').length === 0) {
                            $('.woocommerce-cart-form').before('<div class="woocommerce-error">批发用户需满 ' + wholesaleCartData.minQty + ' 件商品才能结算,请继续添加商品。</div>');
                        } else if (!isUnderMin) {
                            $('.woocommerce-error:contains("批发用户需满")').remove();
                        }
                    }
                });
            });

            // 控制按钮显示/隐藏的函数
            function toggleCheckoutButtons(hide) {
                if (hide) {
                    $('.checkout-button, .gpay-card-info-container-fill, .apple-pay-button, .wc-stripe-cart-checkout-container ul.wc_stripe_cart_payment_methods.active li.wc-stripe-payment-method').hide();
                } else {
                    $('.checkout-button, .gpay-card-info-container-fill, .apple-pay-button, .wc-stripe-cart-checkout-container ul.wc_stripe_cart_payment_methods.active li.wc-stripe-payment-method').show();
                }
            }
        });
    </script>
    <?php
}

// AJAX回调:获取当前购物车总数量
add_action( 'wp_ajax_get_wholesale_cart_qty', 'get_wholesale_cart_qty' );
add_action( 'wp_ajax_nopriv_get_wholesale_cart_qty', 'get_wholesale_cart_qty' );
function get_wholesale_cart_qty() {
    echo WC()->cart->get_cart_contents_count();
    wp_die();
}

核心优化点

  • 用display: none !important的CSS替代JS的remove(),避免AJAX更新后按钮重新渲染恢复显示
  • 监听updated_cart_totals事件(WooCommerce内置的购物车AJAX更新完成事件),确保数量变化后实时验证
  • 添加AJAX回调获取后端真实购物车数量,避免前端计算误差
  • 通过全局变量传递PHP配置参数,让JS逻辑更灵活

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 10:28:27