Woocommerce:Ajax添加自定义折扣价商品至购物车未生效问题
WooCommerce追加销售商品Ajax加入购物车时自定义折扣价不生效的解决方法
问题核心:你传入的product_price参数不会被WooCommerce默认的woocommerce_add_to_cart Ajax动作识别——这个动作的价格计算完全依赖商品本身的定价规则,不会读取自定义传入的价格值。
解决步骤:
1. 修改前端Ajax请求,改用自定义动作
把原Ajax请求里的action从woocommerce_add_to_cart改成自定义动作名称,同时加上安全验证防止CSRF:
$('.add-to-cart-checkbox').click(function() { var product_id = $(this).data('product-id'); var product_price = $(this).data('product-price'); if (this.checked) { $.post(woocommerce_params.ajax_url, { 'action': 'custom_add_upsell_to_cart', 'product_id': product_id, 'discounted_price': product_price, 'security': woocommerce_params.add_to_cart_nonce }, function(response) { console.log(response); // 触发购物车刷新,确保显示最新价格 if (response.success) { $(document.body).trigger('wc_fragment_refresh'); } }); } });
2. 后端添加自定义动作的处理函数
在主题functions.php或自定义插件中添加以下PHP代码,手动处理添加购物车并设置折扣价的逻辑:
add_action('wp_ajax_custom_add_upsell_to_cart', 'custom_add_upsell_to_cart_handler'); add_action('wp_ajax_nopriv_custom_add_upsell_to_cart', 'custom_add_upsell_to_cart_handler'); // 兼容未登录用户 function custom_add_upsell_to_cart_handler() { // 安全验证 if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'woocommerce_add_to_cart')) { wp_send_json_error('无效的安全验证令牌'); } // 检查必填参数 if (!isset($_POST['product_id']) || !isset($_POST['discounted_price'])) { wp_send_json_error('缺少必要参数'); } $product_id = absint($_POST['product_id']); $discounted_price = floatval($_POST['discounted_price']); $product = wc_get_product($product_id); // 验证商品可购买性 if (!$product || !$product->is_purchasable()) { wp_send_json_error('商品不可购买'); } $cart = WC()->cart; $cart_item_key = $cart->find_product_in_cart($cart->generate_cart_id($product_id)); if ($cart_item_key) { // 商品已在购物车,更新价格 $cart->cart_contents[$cart_item_key]['data']->set_price($discounted_price); } else { // 新增商品到购物车并设置折扣价 $cart->add_to_cart($product_id); $cart_item_key = $cart->find_product_in_cart($cart->generate_cart_id($product_id)); if ($cart_item_key) { $cart->cart_contents[$cart_item_key]['data']->set_price($discounted_price); } } // 重新计算购物车总价 $cart->calculate_totals(); wp_send_json_success('商品已添加并应用折扣价'); }
3. 额外注意事项
- 价格合法性校验:可以在后端添加逻辑,比如限制折扣价不低于商品成本价,防止恶意篡改前端价格。
- 库存处理:如果需要,可以在函数中加入库存检查逻辑,确保商品有库存时才允许添加。
内容的提问来源于stack exchange,提问作者n1k1dk
相关产品推荐
相关产品推荐

