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

为什么woocommerce_checkout_update_order_review钩子返回旧运费总额?

解决WooCommerce checkout_update_order_review钩子无法获取最新运费的问题

问题根源

woocommerce_checkout_update_order_review钩子的执行时机早于WooCommerce更新购物车配送费用的流程,因此此时调用WC()->cart->get_shipping_total()只能拿到更新前的旧值,这就是你看到的需要重新输入字段才显示当前值的原因。

解决方案

方法1:改用后置钩子获取最新数据

使用woocommerce_after_checkout_update_order_review钩子,它会在购物车配送信息更新完成后触发,可直接获取最新运费:

function wp_kama_get_latest_shipping_total( $post_data ) {
    parse_str( $post_data, $post_data_array );
    
    $latest_shipping_total = WC()->cart->get_shipping_total();
    
    wc_add_notice( $latest_shipping_total, 'notice' );
    mail("fakeemail@gmail.com", "shipping total", $latest_shipping_total );
}
add_action( 'woocommerce_after_checkout_update_order_review', 'wp_kama_get_latest_shipping_total' );

方法2:在原钩子中手动触发运费计算

如果必须依赖woocommerce_checkout_update_order_review,可以先手动更新客户配送信息并重新计算运费,再获取最新值:

function wp_kama_woocommerce_checkout_update_order_review_action( $post_data ) {
    parse_str( $post_data, $post_data_array );
    
    // 更新客户配送区域信息
    if ( isset( $post_data_array['shipping_country'] ) ) {
        WC()->customer->set_shipping_country( $post_data_array['shipping_country'] );
    }
    if ( isset( $post_data_array['shipping_state'] ) ) {
        WC()->customer->set_shipping_state( $post_data_array['shipping_state'] );
    }
    if ( isset( $post_data_array['shipping_postcode'] ) ) {
        WC()->customer->set_shipping_postcode( $post_data_array['shipping_postcode'] );
    }
    
    // 强制重新计算购物车配送费用
    WC()->cart->calculate_shipping();
    
    // 获取最新运费总额
    $latest_shipping_total = WC()->cart->get_shipping_total();
    
    wc_add_notice( $latest_shipping_total, 'notice' );
    mail("fakeemail@gmail.com", "shipping total", $latest_shipping_total );
}
add_action( 'woocommerce_checkout_update_order_review', 'wp_kama_woocommerce_checkout_update_order_review_action' );

为什么之前的方法无效

你之前尝试直接读取$_POST或解析$post_data,只能获取用户提交的原始参数,但此时WooCommerce还未基于这些参数重新计算购物车运费,因此购物车对象中存储的仍是更新前的旧数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:43:11