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

如何通过Ajax向WooCommerce购物车片段传递自定义数据?

WooCommerce Ajax添加购物车并传递自定义数据的正确实现

原代码存在的问题

  • 未接收前端Ajax传递的自定义参数,而是硬编码固定值
  • 调用add_to_cart方法时,未将自定义购物车项数据传入
  • jQuery逻辑判断误用位运算符&,应改为逻辑与&&
  • 缺少自定义数据在购物车片段中的显示逻辑

修正后的jQuery代码

jQuery(document).ready(function($) {
    $('.single_add_to_cart_button').on('click', function(e){ 
        e.preventDefault();
        var thisbutton = $(this),
            $form = thisbutton.closest('form.cart'),
            id = thisbutton.val(),
            product_qty = $form.find('input[name="quantity"]').val() || 1,
            product_id = $form.find('input[name="product_id"]').val() || id,
            variation_id = $form.find('input[name="variation_id"]').val() || 0;
            
        var data = {
            action: 'ql_woocommerce_ajax_add_to_cart',
            product_id: product_id,
            product_sku: '',
            quantity: product_qty,
            variation_id: variation_id,
            name: 'Tom', // 可根据需求动态获取值,比如从输入框读取
        };
        
        $.ajax({
            type: 'post',
            url: wc_add_to_cart_params.ajax_url,
            data: data,
            beforeSend: function (response) {
                thisbutton.removeClass('added').addClass('loading');
            },
            complete: function (response) {
                thisbutton.addClass('added').removeClass('loading');
            }, 
            success: function (response) { 
                // 修正逻辑运算符为 &&
                if (response.error && response.product_url) {
                    window.location = response.product_url;
                    return;
                } else { 
                    $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, thisbutton]);
                } 
                console.log(wc_add_to_cart_params.ajax_url, data);
            }, 
        }); 
    }); 
});

修正后的PHP代码

add_action('wp_ajax_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart'); 
add_action('wp_ajax_nopriv_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart');          
function ql_woocommerce_ajax_add_to_cart() {  

    $product_id = apply_filters('ql_woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
    $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
    $variation_id = absint($_POST['variation_id']);
    $passed_validation = apply_filters('ql_woocommerce_add_to_cart_validation', true, $product_id, $quantity);
    $product_status = get_post_status($product_id); 
    
    // 接收前端传递的自定义参数并做安全处理
    $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
    $cart_item_data = array();
    if (!empty($name)) {
        $cart_item_data['name'] = $name;
        // 添加唯一键,确保相同产品不同自定义值可作为独立项加入购物车
        $cart_item_data['unique_key'] = md5(microtime().$name);
    }

    // 调用add_to_cart时传入自定义购物车项数据
    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, array(), $cart_item_data) && 'publish' === $product_status) { 
        do_action('ql_woocommerce_ajax_added_to_cart', $product_id);

        if ('yes' === get_option('ql_woocommerce_cart_redirect_after_add')) { 
            wc_add_to_cart_message(array($product_id => $quantity), true); 
        } 

        WC_AJAX::get_refreshed_fragments(); 
    } else { 
        $data = array( 
            'error' => true,
            'product_url' => apply_filters('ql_woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id)
        );
        echo wp_send_json($data);
    }
    wp_die();
}

// 添加过滤器,让自定义数据显示在购物车片段和购物车页面中
add_filter('woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2);
function display_custom_cart_item_data($item_data, $cart_item) {
    if (isset($cart_item['name'])) {
        $item_data[] = array(
            'key' => __('名称', 'woocommerce'),
            'value' => wc_clean($cart_item['name'])
        );
    }
    return $item_data;
}

关键修改说明

  1. 接收自定义参数:PHP中通过$_POST['name']获取前端传递的值,并用sanitize_text_field确保数据安全
  2. 传递自定义数据到购物车:调用WC()->cart->add_to_cart时传入第五个参数$cart_item_data,同时添加unique_key避免相同产品不同自定义值被合并
  3. 修复逻辑判断:将jQuery中的位运算符&改为逻辑与&&,避免判断逻辑错误
  4. 显示自定义数据:通过woocommerce_get_item_data过滤器,将自定义数据渲染到购物车片段、迷你购物车及购物车页面中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:20:34