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

WooCommerce中点击加购按钮时如何通过JavaScript添加自定义商品数据

解决方法

你可以通过adding_to_cart事件直接追加参数到加购请求数据中,配合后端钩子存储自定义购物车数据即可实现需求,具体操作如下:

1. 前端JS代码调整

你只需要在adding_to_cart事件回调中,把读取到的URL参数直接追加到事件回调的data对象上,WooCommerce发起加购AJAX请求时会自动携带这些自定义参数:

$(document.body).on('adding_to_cart', function( button, data ) {
    const queryString = window.location.search;
    const urlParams  = new URLSearchParams(queryString);
    // 把URL参数追加到加购数据中
    data.custom_color = urlParams.get('color');
    data.custom_hex = urlParams.get('hex');
    data.custom_extracost = urlParams.get('price');
})

注意:参数名建议加自定义前缀,避免和WooCommerce原生参数冲突

2. 后端接收存储自定义数据

前端加购请求携带自定义参数后,你需要用woocommerce_add_cart_item_data钩子把参数存储到购物车项的元数据中:

add_filter( 'woocommerce_add_cart_item_data', 'save_custom_cart_params', 10, 3 );
function save_custom_cart_params( $cart_item_data, $product_id, $variation_id ) {
    // 接收前端传递的自定义参数
    if( isset( $_REQUEST['custom_color'] ) ) {
        $cart_item_data['custom_color'] = sanitize_text_field( $_REQUEST['custom_color'] );
    }
    if( isset( $_REQUEST['custom_hex'] ) ) {
        $cart_item_data['custom_hex'] = sanitize_hex_color( $_REQUEST['custom_hex'] );
    }
    if( isset( $_REQUEST['custom_extracost'] ) ) {
        $cart_item_data['custom_extracost'] = floatval( $_REQUEST['custom_extracost'] );
        // 如果需要额外计算价格,可以配合woocommerce_before_calculate_totals钩子实现
    }
    // 生成唯一键避免同商品不同参数被合并
    $cart_item_data['unique_key'] = md5( microtime().rand() );
    return $cart_item_data;
}

3. 自定义数据后续展示

如果需要在购物车页、结算页、订单详情中展示这些自定义数据,调用woocommerce_get_item_data钩子添加显示字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:21:01