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

WooCommerce:商品页JS计算的自定义价格如何传递到购物车函数

解决方案

1. 前端传递自定义价格到后台

在商品页面通过JavaScript计算自定义价格后,将其作为隐藏字段添加到加入购物车表单,提交时同步传递给后台:

document.addEventListener('DOMContentLoaded', function() {
    const productForm = document.querySelector('form.cart');
    // 替换为你的实际价格计算逻辑
    const basePrice = 100;
    const customPrice = basePrice + 50;

    // 创建隐藏字段存储自定义价格
    const priceInput = document.createElement('input');
    priceInput.type = 'hidden';
    priceInput.name = 'custom_product_price';
    priceInput.value = customPrice;
    productForm.appendChild(priceInput);

    // 兼容AJAX加入购物车场景
    const addBtn = document.querySelector('.single_add_to_cart_button');
    addBtn.addEventListener('click', () => {
        if (!productForm.querySelector('input[name="custom_product_price"]')) {
            productForm.appendChild(priceInput);
        }
    });
});

2. 后台接收并存储自定义价格到购物车项

通过woocommerce_add_cart_item_data钩子,将前端传递的自定义价格绑定到对应购物车项的元数据中:

add_filter('woocommerce_add_cart_item_data', 'save_custom_price_to_cart', 10, 3);
function save_custom_price_to_cart($cart_item_data, $product_id, $variation_id) {
    if (isset($_POST['custom_product_price']) && is_numeric($_POST['custom_product_price'])) {
        $cart_item_data['custom_price'] = floatval($_POST['custom_product_price']);
        // 添加唯一标识,确保每次提交的自定义价格项视为独立条目(可选)
        $cart_item_data['unique_custom_price_key'] = md5(microtime());
    }
    return $cart_item_data;
}

3. 修改价格计算逻辑,使用自定义价格

更新你原有的add_custom_price函数,从购物车项元数据中读取自定义价格,而非固定值:

add_action('woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
function add_custom_price($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;
    if (did_action('woocommerce_before_calculate_totals') >= 2) return;

    foreach ($cart->get_cart() as $cart_item) {
        if (isset($cart_item['custom_price'])) {
            $cart_item['data']->set_price($cart_item['custom_price']);
        }
    }
}

4. 限制购物车仅允许单个商品

通过woocommerce_add_to_cart_validation钩子,控制购物车最多只能有一个商品:

add_filter('woocommerce_add_to_cart_validation', 'limit_cart_to_single_item', 10, 5);
function limit_cart_to_single_item($passed, $product_id, $quantity) {
    if (WC()->cart->get_cart_contents_count() >= 1) {
        // 清空现有购物车后添加新商品
        WC()->cart->empty_cart();
        // 可选:添加提示信息
        // wc_add_notice('购物车仅支持添加一件商品', 'notice');
    }
    return $passed;
}

可选:购物车页面同步显示自定义价格

确保购物车页面显示的价格与自定义价格一致:

add_filter('woocommerce_cart_item_price', 'display_custom_cart_price', 10, 3);
function display_custom_cart_price($price, $cart_item) {
    if (isset($cart_item['custom_price'])) {
        $price = wc_price($cart_item['custom_price']);
    }
    return $price;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:38:17