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

使用woocommerce_product_get_price钩子后结账与购物车价格不一致

解决方案

要解决结账页面显示标准价格、订单记录错误价格的问题,需要确保购物车实际价格计算、结账页面价格显示、订单项目价格保存三个环节都使用自定义字段precio_web的值。以下是完整的代码实现,替换你当前子主题functions.php中的相关代码即可:

1. 统一判断用户角色条件

先封装一个判断函数,用来确认当前用户是否为访客或customer角色:

function is_web_price_eligible_user() {
    // 访客用户
    if ( ! is_user_logged_in() ) {
        return true;
    }
    // 已登录的customer角色用户
    $current_user = wp_get_current_user();
    return in_array( 'customer', (array) $current_user->roles );
}

2. 修正购物车实际价格计算

确保购物车项目的实际价格被替换为自定义价格(之前的代码可能仅修改了显示,未修改实际计算值):

add_action( 'woocommerce_before_calculate_totals', 'apply_web_price_to_cart', 20 );
function apply_web_price_to_cart( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    if ( ! is_web_price_eligible_user() ) return;

    foreach ( $cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];
        $web_price = get_field( 'precio_web', $product_id );
        
        if ( $web_price ) {
            // 设置购物车项目的实际价格
            $cart_item['data']->set_price( $web_price );
        }
    }
}

3. 同步结账页面价格显示

强制结账页面的小计显示自定义价格计算的结果:

add_filter( 'woocommerce_cart_item_subtotal', 'show_web_price_in_checkout', 20, 3 );
function show_web_price_in_checkout( $subtotal_html, $cart_item, $cart_item_key ) {
    if ( ! is_checkout() || ! is_web_price_eligible_user() ) return $subtotal_html;

    $product_id = $cart_item['product_id'];
    $web_price = get_field( 'precio_web', $product_id );
    
    if ( $web_price ) {
        $quantity = $cart_item['quantity'];
        $subtotal_html = wc_price( $web_price * $quantity );
    }
    return $subtotal_html;
}

4. 保存自定义价格到订单记录

在创建订单时,将自定义价格写入订单项目,确保订单记录的价格正确:

add_action( 'woocommerce_checkout_create_order_line_item', 'save_web_price_to_order', 20, 4 );
function save_web_price_to_order( $order_item, $cart_item_key, $cart_item, $order ) {
    if ( ! is_web_price_eligible_user() ) return;

    $product_id = $cart_item['product_id'];
    $web_price = get_field( 'precio_web', $product_id );
    
    if ( $web_price ) {
        // 设置订单项目的小计和总价
        $order_item->set_subtotal( $web_price * $cart_item['quantity'] );
        $order_item->set_total( $web_price * $cart_item['quantity'] );
        // 添加自定义元数据,方便在订单中查看该价格来源
        $order_item->add_meta_data( '网页专属价格', wc_price( $web_price ), true );
    }
}

注意事项

  • 确保ACF字段precio_web的返回格式为数值类型(而非字符串),避免计算错误。
  • 测试前清空购物车,确保新的价格规则生效。
  • 代码需添加到子主题的functions.php中,避免主题更新丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:05:31