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

WooCommerce变量产品数量按钮异常:设置数量未同步至购物车

问题分析

变量产品数量同步异常的核心原因:

  • 变量产品在商店循环中生成的添加按钮是<button>表单提交按钮,而非简单产品的<a>链接标签,原JS代码仅针对<a.add_to_cart_button>处理,无法覆盖变量产品的提交逻辑。
  • 变量产品通过表单AJAX提交购物车,原JS修改data-quantity和href的逻辑不适用于表单提交场景,导致数量参数未正确传递到购物车请求中。
修复代码

1. 调整PHP函数(优化元素渲染逻辑)

移除默认的变量产品添加按钮,避免重复渲染,确保数量输入与表单关联正确:

/**
 * 循环中显示数量输入框
 */
function custom_wc_template_loop_quantity_input() {
    global $product;

    if ( $product && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        if ( $product->is_type( 'simple' ) ) {
            woocommerce_quantity_input(
                array(
                    'min_value' => 1,
                    'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
                )
            );
        } elseif ( $product->is_type( 'variable' ) ) {
            // 移除默认添加按钮,避免重复渲染
            remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
            woocommerce_variable_add_to_cart();
        }
    }
}
add_action( 'woocommerce_after_shop_loop_item', 'custom_wc_template_loop_quantity_input', 9 );

2. 替换JS脚本,适配两种产品类型的提交逻辑

同时处理简单产品的链接式提交和变量产品的表单AJAX提交,确保数量正确传递:

/**
 * 添加数量变化监听脚本
 */
function custom_wc_add_qty_change_script() {
    ?>
    <script>
        (function ($) {
            // 监听所有数量输入框的变化事件
            $(document).on("input change", "li.product .quantity input.qty", function () {
                const $qtyInput = $(this);
                const $productItem = $qtyInput.closest("li.product");

                // 处理简单产品的链接式添加按钮
                const $simpleAddBtn = $productItem.find("a.add_to_cart_button");
                if ($simpleAddBtn.length) {
                    $simpleAddBtn.attr("data-quantity", $qtyInput.val());
                    $simpleAddBtn.attr("href", `?add-to-cart=${$simpleAddBtn.attr("data-product_id")}&quantity=${$qtyInput.val()}`);
                }

                // 处理变量产品的表单AJAX提交
                const $variableForm = $productItem.find("form.variations_form");
                if ($variableForm.length) {
                    $variableForm.on("submit", function (e) {
                        e.preventDefault();
                        let formData = $(this).serializeArray();
                        // 更新表单中的quantity参数
                        const qtyIndex = formData.findIndex(item => item.name === 'quantity');
                        if (qtyIndex !== -1) {
                            formData[qtyIndex].value = $qtyInput.val();
                        } else {
                            formData.push({name: 'quantity', value: $qtyInput.val()});
                        }
                        // 调用WooCommerce内置AJAX接口添加购物车
                        $.ajax({
                            url: wc_add_to_cart_params.wc_ajax_url.replace('%%endpoint%%', 'add_to_cart'),
                            type: 'POST',
                            data: formData,
                            success: function(response) {
                                if (response.error && response.product_url) {
                                    window.location = response.product_url;
                                    return;
                                }
                                // 触发购物车更新事件,同步页面状态
                                $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $variableForm]);
                            }
                        });
                    });
                }
            });
        })(jQuery);
    </script>
    <?php
}
add_action( 'wp_head', 'custom_wc_add_qty_change_script', 20 );
额外注意事项
  • 确保主题未禁用WooCommerce全局变量wc_add_to_cart_params,否则AJAX提交会失效。
  • 修改代码后请清除网站缓存,避免旧脚本残留影响测试结果。

内容的提问来源于stack exchange,提问作者Min Su Wai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:25:33