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

如何通过URL在WooCommerce中添加带指定属性的多个商品至购物车

多属性商品批量加入购物车实现方案

原写法失效原因

你当前用逗号分隔多组加购参数的写法不符合WooCommerce默认的参数解析规则,系统无法识别多组商品和属性的对应关系。

方案1:官方原生URL传参实现

WooCommerce 3.0及以上版本本身支持通过下标数组参数绑定多组商品的属性信息,你只需要按照相同下标对应同一商品的所有参数的规则拼接URL即可。
针对你的需求,正确的URL格式如下:
https://www.cps.com.ro/cart?add-to-cart[0]=9354&attribute[0]=24&quantity[0]=1&add-to-cart[1]=9353&attribute[1]=2&quantity[1]=1

使用注意事项:

  • 如果商品有多个自定义属性,参数名需要和后台属性设置的slug完全匹配,比如attribute_pa_color[0]=black&attribute_pa_size[0]=xl
  • 部分安全防护、缓存类插件可能会拦截带数组格式的URL参数,遇403错误可调整插件放行规则

方案2:自定义代码实现(兼容性更强)

如果URL传参方式存在兼容问题,可以将以下代码添加到当前主题的functions.php文件中,自定义批量加购逻辑:

// 批量加购自定义逻辑
add_action('init', 'custom_batch_add_to_cart');
function custom_batch_add_to_cart() {
    if (!isset($_GET['custom_batch_add']) || !is_array($_GET['custom_batch_add'])) return;
    
    foreach ($_GET['custom_batch_add'] as $item) {
        $product_id = absint($item['id']);
        $quantity = isset($item['qty']) ? absint($item['qty']) : 1;
        $attributes = isset($item['attr']) ? array_map('sanitize_text_field', $item['attr']) : [];
        WC()->cart->add_to_cart($product_id, $quantity, 0, $attributes);
    }
    
    wp_safe_redirect(wc_get_cart_url());
    exit;
}

代码部署后,使用如下格式的URL即可实现批量加购:
https://www.cps.com.ro/?custom_batch_add[0][id]=9354&custom_batch_add[0][attr][attribute]=24&custom_batch_add[1][id]=9353&custom_batch_add[1][attr][attribute]=2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:42:02