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

自定义WooCommerce Ajax加入购物车功能异常问题

问题:自定义AJAX加购商品返回成功,但购物车无显示

问题详情

通过JavaScript发起AJAX请求,传递商品ID到WordPress的admin-ajax.php,在主题functions.php中调用WooCommerce的add_to_cart()方法,接口返回成功提示,但前端购物车页面、结账页面均看不到添加的商品。正常商品页的默认加购按钮可正常工作,已排查插件(仅保留Elementor和WooCommerce)、主题(Hello Elementor)及WooCommerce状态无异常,更换多个商品ID问题依旧。

所用代码

HTML & JavaScript

<button onclick="f1()" style="margin-block:100px;margin-inline:auto;">✅</button>
<script>
    function f1(){
        // const cartItems=[9660, 9568, 8625]
        const cartItems=9568
        const data = {
            action: 'AddtocartF',
            ProductsToPay: JSON.stringify(cartItems)
        };
        fetch('https://9effa.ma/wp-admin/admin-ajax.php', {
            method: 'POST',
            body: new URLSearchParams(data),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        })
            .then(response => response.json())
            .then(data => {
                console.log(data)
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }
</script>

PHP(functions.php)

add_action('wp_ajax_AddtocartF', 'AddtocartFunction');
add_action('wp_ajax_nopriv_AddtocartF', 'AddtocartFunction');

function AddtocartFunction(){
    if (!isset($_POST['ProductsToPay'])) {
        wp_send_json_error(['message' => "Veuillez ajouter les produits au panier avant de passer au paiement."]);
    }
    $product_id = $_POST['ProductsToPay'];
    $quantity = 1;
    $WC_Cart = new WC_Cart();
    $result = $WC_Cart->add_to_cart($product_id, $quantity);
    if (is_wp_error($result)) {
        // Handle the error case
        wp_send_json_error(['message' => $result->get_error_message()]);
    } else {
        // Product added successfully
        $response = ['success' => true, 'message' => 'Product added to cart', 'id' => $product_id, 'result value: ' => $result];
        wp_send_json_success($response);
    }
    wp_die();
}

控制台返回结果

{
    "success": true,
    "data": {
        "success": true,
        "message": "Product added to cart",
        "id": "9568",
        "result value: ": "621d187a8e1a345cc07422a61c669654"
    }
}

问题原因

  1. 错误实例化购物车对象:手动new WC_Cart()会创建一个独立的临时购物车实例,不会关联到当前用户的会话(cookie),商品被添加到了这个临时实例中,而非用户实际使用的购物车。
  2. 未解析JSON数据:JavaScript中用JSON.stringify()处理了商品ID,但PHP中直接获取原始字符串,虽然单个ID能勉强识别,但格式不规范,且无法支持批量加购场景。

修复方案

1. 修正PHP代码(核心修复)

改用WooCommerce全局购物车对象,同时解析JSON数据:

add_action('wp_ajax_AddtocartF', 'AddtocartFunction');
add_action('wp_ajax_nopriv_AddtocartF', 'AddtocartFunction');

function AddtocartFunction(){
    if (!isset($_POST['ProductsToPay'])) {
        wp_send_json_error(['message' => "Veuillez ajouter les produits au panier avant de passer au paiement."]);
    }
    
    // 解析传递的JSON字符串,处理转义字符
    $products = json_decode(stripslashes($_POST['ProductsToPay']), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        wp_send_json_error(['message' => "Format de produit invalide."]);
    }
    
    // 统一转为数组,支持单个或多个商品ID
    $product_ids = is_array($products) ? $products : [$products];
    
    $success_count = 0;
    foreach ($product_ids as $product_id) {
        $product_id = absint($product_id);
        if (!$product_id) continue;
        
        // 使用WooCommerce全局购物车对象,关联用户会话
        $result = WC()->cart->add_to_cart($product_id, 1);
        
        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        } elseif ($result) {
            $success_count++;
        }
    }
    
    if ($success_count > 0) {
        $response = [
            'success' => true,
            'message' => sprintf('%d produit(s) ajouté(s) au panier', $success_count),
            'added_ids' => $product_ids
        ];
        wp_send_json_success($response);
    } else {
        wp_send_json_error(['message' => "Aucun produit n'a pu être ajouté."]);
    }
    
    wp_die();
}

2. 优化JavaScript代码(可选)

添加会话凭证确保购物车关联,同时支持批量加购,并可触发购物车UI更新:

function f1(){
    // 支持单个ID或数组形式的多个ID
    const cartItems = 9568; // 或者 [9660, 9568, 8625]
    const data = {
        action: 'AddtocartF',
        ProductsToPay: JSON.stringify(cartItems)
    };
    fetch('https://9effa.ma/wp-admin/admin-ajax.php', {
        method: 'POST',
        body: new URLSearchParams(data),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        // 确保携带用户会话cookie,关联购物车
        credentials: 'same-origin'
    })
    .then(response => response.json())
    .then(data => {
        console.log(data);
        // 触发WooCommerce购物车UI更新事件,实时刷新购物车计数
        if (data.success) {
            document.body.dispatchEvent(new Event('wc_fragment_refresh'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 04:40:24