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

在WooCommerce中通过JQuery和Ajax添加多规格商品至购物车

解决WooCommerce Ajax批量添加商品变体到购物车的问题

默认的WooCommerce add_to_cart Ajax端点仅支持单个商品变体的添加请求,无法直接接收数组格式的多商品数据,这就是你发送数组multi_data无效的原因。下面提供两种可行的解决方法:

方法一:循环调用单个添加接口(快速实现)

通过循环遍历多商品数据,逐个调用add_to_cart接口。这种方式无需修改后端,直接在前端调整代码即可:

jQuery(function($) {
    $(document.body).on('click', '#button', function(e) {
        const multi_data = [
            { product_id: 592, quantity: 2 },
            { product_id: 593, quantity: 1 },
            { product_id: 594, quantity: 3 }
        ];

        // 循环处理每个商品
        multi_data.forEach(item => {
            $.ajax({
                type: 'POST',
                url: wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'),
                data: item,
                success: function(res) {
                    console.log(`商品${item.product_id}添加结果:`, res);
                },
                error: function(err) {
                    console.error(`商品${item.product_id}添加失败:`, err);
                }
            });
        });
    });
});

方法二:自定义后端Ajax端点(推荐,单次请求)

通过在主题的functions.php中添加自定义Ajax端点,专门处理批量添加逻辑,这样可以用一次请求完成所有商品的添加:

第一步:添加后端自定义端点

在主题的functions.php文件中插入以下代码:

// 注册批量添加到购物车的Ajax端点
add_action('wp_ajax_batch_add_to_cart', 'handle_batch_add_to_cart');
add_action('wp_ajax_nopriv_batch_add_to_cart', 'handle_batch_add_to_cart');

function handle_batch_add_to_cart() {
    // 检查用户权限和请求有效性
    if (!isset($_POST['items']) || !is_array($_POST['items'])) {
        wp_send_json_error('无效的商品数据');
    }

    $items = $_POST['items'];
    $results = [];

    foreach ($items as $item) {
        $product_id = isset($item['product_id']) ? intval($item['product_id']) : 0;
        $quantity = isset($item['quantity']) ? intval($item['quantity']) : 1;

        if (!$product_id) {
            $results[] = [
                'product_id' => $product_id,
                'status' => 'error',
                'message' => '商品ID无效'
            ];
            continue;
        }

        // 检查商品是否存在且为变体
        $product = wc_get_product($product_id);
        if (!$product || !$product->is_type('variation')) {
            $results[] = [
                'product_id' => $product_id,
                'status' => 'error',
                'message' => '不是有效的商品变体'
            ];
            continue;
        }

        // 添加到购物车
        $cart_item_key = WC()->cart->add_to_cart($product_id, $quantity);
        if ($cart_item_key) {
            $results[] = [
                'product_id' => $product_id,
                'status' => 'success',
                'message' => '添加成功',
                'cart_item_key' => $cart_item_key
            ];
        } else {
            $results[] = [
                'product_id' => $product_id,
                'status' => 'error',
                'message' => '添加失败'
            ];
        }
    }

    wp_send_json_success($results);
}

第二步:前端调用自定义端点

修改前端JavaScript代码,调用新的自定义端点:

jQuery(function($) {
    $(document.body).on('click', '#button', function(e) {
        const multi_data = [
            { product_id: 592, quantity: 2 },
            { product_id: 593, quantity: 1 },
            { product_id: 594, quantity: 3 }
        ];

        $.ajax({
            type: 'POST',
            url: wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'batch_add_to_cart'),
            data: { items: multi_data },
            success: function(res) {
                console.log('批量添加结果:', res.data);
                // 可选:更新购物车显示
                $(document.body).trigger('wc_fragment_refresh');
            },
            error: function(err) {
                console.error('批量添加失败:', err);
            }
        });
    });
});

注意:第二种方法需要确保主题的functions.php修改正确,并且测试商品变体ID的有效性,避免无效请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 06:31:14