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

WooCommerce未登录用户VAT字段非空时10%折扣实现求助

WooCommerce B2B 10%折扣实现方案(未登录用户版)

原代码问题分析

你之前的代码无效主要有两个原因:

  • 直接调用$_POST['billing_cod_fiscal']无法持久获取结账字段值,woocommerce_cart_calculate_fees钩子触发时POST请求上下文已丢失
  • 使用WC()->cart->subtotal会包含VAT金额,不符合你"不含VAT及运费的subtotal"的要求

正确实现代码

// 监听结账字段更新,将VAT号存入会话
add_action('woocommerce_checkout_update_order_review', 'save_vat_number_to_session');
function save_vat_number_to_session($posted_data) {
    parse_str($posted_data, $post_data);
    
    // 检查VAT号字段(这里假设字段名是billing_cod_fiscal,和你原代码一致)
    if (!empty($post_data['billing_cod_fiscal'])) {
        WC()->session->set('b2b_vat_number', sanitize_text_field($post_data['billing_cod_fiscal']));
    } else {
        WC()->session->set('b2b_vat_number', '');
    }
}

// 计算并应用B2B折扣
add_action('woocommerce_cart_calculate_fees', 'apply_b2b_discount');
function apply_b2b_discount() {
    // 仅对未登录用户生效,且会话中存在非空VAT号
    if (!is_user_logged_in() && !empty(WC()->session->get('b2b_vat_number'))) {
        // 获取不含VAT的购物车小计(不含运费)
        $subtotal_ex_tax = WC()->cart->get_subtotal_ex_tax();
        
        // 计算10%折扣
        $discount_amount = $subtotal_ex_tax * 0.1;
        
        // 添加折扣到购物车,负数表示折扣
        WC()->cart->add_fee(__('B2B 10%折扣', 'woocommerce'), -$discount_amount, true);
    }
}

// 清空购物车时移除会话中的VAT号
add_action('woocommerce_cart_emptied', 'clear_vat_number_session');
function clear_vat_number_session() {
    WC()->session->set('b2b_vat_number', '');
}

代码关键点说明

  • 会话存储VAT号:通过woocommerce_checkout_update_order_review钩子捕获结账页面的字段提交,将VAT号存入WooCommerce会话,确保在整个结账流程中都能读取到最新值
  • 不含VAT的小计:使用WC()->cart->get_subtotal_ex_tax()获取完全不含VAT的购物车商品总价,符合需求
  • 实时检测:每次计算购物车费用时都会检查会话中的VAT号,用户修改字段后折扣会自动更新
  • 清理会话:购物车清空时移除会话中的VAT号,避免下次购物时错误应用折扣

内容的提问来源于stack exchange,提问作者Antal Szabó

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 01:44:57