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

为WooCommerce购物车组件添加数量选择器及Ajax交互功能

解决WooCommerce迷你购物车数量修改无响应问题

你现有的代码仅实现了数量选择器的显示,缺少后端Ajax处理逻辑和前端请求触发代码,以下是完整解决方案:

一、完善PHP代码(含Ajax处理)

将以下代码添加到主题的functions.php文件中:

// 在迷你购物车显示数量选择器
add_filter( 'woocommerce_widget_cart_item_quantity', 'add_minicart_quantity_fields', 10, 3 );
function add_minicart_quantity_fields( $html, $cart_item, $cart_item_key ) {
    // 给数量输入框添加cart_item_key属性,方便Ajax识别
    $quantity_html = woocommerce_quantity_input(
        array(
            'input_value' => $cart_item['quantity'],
            'min_value'   => 1,
            'max_value'   => $cart_item['data']->get_max_purchase_quantity()
        ),
        $cart_item['data'],
        false
    );
    // 替换默认输入框,添加自定义属性
    $quantity_html = str_replace( 'type="number"', 'type="number" data-cart-item-key="' . esc_attr( $cart_item_key ) . '"', $quantity_html );
    
    $product_price = apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $cart_item['data'] ), $cart_item, $cart_item_key );
    return $quantity_html . $product_price;
}

// 注册Ajax更新动作(登录用户)
add_action( 'wp_ajax_update_minicart_quantity', 'update_minicart_quantity' );
// 注册Ajax更新动作(未登录用户)
add_action( 'wp_ajax_nopriv_update_minicart_quantity', 'update_minicart_quantity' );

// 处理迷你购物车数量更新的Ajax请求
function update_minicart_quantity() {
    // 验证非ce攻击和权限
    if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( $_POST['security'], 'woocommerce-cart' ) ) {
        wp_send_json_error( '无效的安全验证' );
    }

    $cart_item_key = sanitize_text_field( $_POST['cart_item_key'] );
    $quantity = absint( $_POST['quantity'] );

    // 更新购物车数量
    if ( WC()->cart->set_quantity( $cart_item_key, $quantity ) ) {
        // 获取更新后的迷你购物车HTML
        ob_start();
        woocommerce_mini_cart();
        $mini_cart_html = ob_get_clean();
        
        wp_send_json_success( array(
            'mini_cart_html' => $mini_cart_html,
            'cart_total'     => WC()->cart->get_cart_total()
        ) );
    } else {
        wp_send_json_error( '数量更新失败' );
    }
}

二、添加前端JavaScript代码

将以下代码添加到主题的自定义JS文件中,或者通过wp_enqueue_script挂载:

jQuery(document).ready(function($) {
    // 监听迷你购物车数量输入框的变化
    $(document).on('change input', '.widget_shopping_cart .quantity input[type="number"]', function() {
        var $input = $(this);
        var cartItemKey = $input.data('cart-item-key');
        var quantity = parseInt($input.val());

        // 数量不能小于1
        if (quantity < 1) {
            quantity = 1;
            $input.val(1);
        }

        // 发送Ajax请求
        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: {
                action: 'update_minicart_quantity',
                security: wc_add_to_cart_params.cart_nonce,
                cart_item_key: cartItemKey,
                quantity: quantity
            },
            beforeSend: function() {
                $input.prop('disabled', true);
                $('.widget_shopping_cart').addClass('loading');
            },
            success: function(response) {
                if (response.success) {
                    // 更新迷你购物车HTML
                    $('.widget_shopping_cart').html(response.data.mini_cart_html);
                    // 更新页面上的购物车总数(如果有)
                    $('.cart-contents').html(response.data.cart_total);
                } else {
                    alert(response.data);
                }
            },
            complete: function() {
                $input.prop('disabled', false);
                $('.widget_shopping_cart').removeClass('loading');
            }
        });
    });

    // 监听加减按钮(如果WooCommerce默认加载了数量按钮)
    $(document).on('click', '.widget_shopping_cart .quantity .plus, .widget_shopping_cart .quantity .minus', function() {
        var $input = $(this).siblings('input[type="number"]');
        $input.trigger('change');
    });
});

三、可选:优化数量选择器样式

迷你购物车空间有限,可添加以下CSS调整样式:

.widget_shopping_cart .quantity {
    display: inline-flex;
    align-items: center;
    margin-right: 10px;
}

.widget_shopping_cart .quantity input[type="number"] {
    width: 50px;
    text-align: center;
    margin: 0 5px;
}

.widget_shopping_cart .loading {
    opacity: 0.7;
    pointer-events: none;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:06:32