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

如何通过jQuery和Ajax在WooCommerce中添加产品变体到购物车

问题

无法使用jQuery和Ajax将产品变体添加到购物车。使用代码时,添加的是父可变产品而非指定变体:例如选择了价格为45美元的蓝色T恤变体,但最终购物车中显示的是价格30美元的父产品,正确显示应为“T恤 - 蓝色 45美元”,实际显示为“T恤 30美元”。使用的代码如下:

jQuery(document).ready(function($) {
    $(document.body).on('click', '#button', function(e) {
        const data = {
            product_id: 592,
            quantity: 2,
            variation_id: 1017,
        };

        $.ajax({
            type: 'POST',
            url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' ),
            data: data,
            success: function(res) {
                console.log('added');
            },
        });
    });
});

解决方法

WooCommerce的AJAX添加变体购物车,仅传递variation_id和product_id是不够的,必须同时提交该变体对应的属性参数,还要添加安全验证参数,否则系统无法识别具体变体,会默认添加父产品。

关键修正点:

  • 添加variation对象,包含变体对应的所有属性键值对(属性键格式为attribute_属性slug,比如颜色属性slug是pa_color,键就是attribute_pa_color)
  • 加入security参数,使用wc_add_to_cart_params.add_to_cart_nonce做CSRF验证,避免请求被拒绝
  • 可选:成功后触发wc_fragment_refresh事件,同步页面购物车显示

修正后的完整代码:

jQuery(document).ready(function($) {
    $(document.body).on('click', '#button', function(e) {
        e.preventDefault(); // 阻止默认跳转行为

        const data = {
            product_id: 592,
            quantity: 2,
            variation_id: 1017,
            // 变体属性:键为attribute_属性slug,值为属性值的slug
            variation: {
                'attribute_pa_color': 'blue' // 替换为你的属性slug和对应值
            },
            // 安全验证nonce,必须添加
            security: wc_add_to_cart_params.add_to_cart_nonce
        };

        $.ajax({
            type: 'POST',
            url: wc_add_to_cart_params.wc_ajax_url.replace('%%endpoint%%', 'add_to_cart'),
            data: data,
            success: function(res) {
                if (res.error) {
                    console.error('添加失败:', res.error);
                } else {
                    console.log('变体添加成功');
                    // 触发购物车刷新,同步页面显示
                    $(document.body).trigger('wc_fragment_refresh');
                }
            },
            error: function(xhr) {
                console.error('请求异常:', xhr.responseText);
            }
        });
    });
});

额外说明:

  • 如果变体有多个属性(比如颜色+尺码),需要把所有属性都加入variation对象,例如:
    variation: {
        'attribute_pa_color': 'blue',
        'attribute_pa_size': 'medium'
    }
    
  • 属性slug可在WooCommerce后台「产品 > 属性」中查看对应属性的slug值
  • 若仍有问题,可在控制台查看AJAX返回的错误信息,排查参数是否匹配变体的实际属性

内容的提问来源于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:05