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

WooCommerce:如何在付款前获取运费并通过指定钩子显示?

解决方案:在结账付款前获取并显示运费

当用户在结账页面选择配送方式后,WooCommerce会实时更新购物车的运费数据,无需依赖未创建的订单对象,直接通过WC()->cart即可获取所需信息。以下是适配woocommerce_review_order_before_payment钩子的实现代码:

add_action( 'woocommerce_review_order_before_payment', 'display_shipping_cost_before_payment' );
function display_shipping_cost_before_payment() {
    // 判断购物车是否需要配送
    if ( WC()->cart->needs_shipping() ) {
        $shipping_total = WC()->cart->get_shipping_total();
        
        if ( $shipping_total > 0 ) {
            // 获取用户选择的配送方式名称
            $chosen_method_id = WC()->session->get('chosen_shipping_methods')[0];
            $shipping_method = WC()->shipping->get_shipping_method( $chosen_method_id );
            $method_title = $shipping_method ? $shipping_method->get_title() : '未知配送方式';
            ?>
            <div class="shipping-cost-summary" style="margin: 1em 0; padding: 1em; border: 1px solid #eee;">
                <h4>配送费用详情</h4>
                <p><strong>所选配送方式:</strong><?php echo esc_html( $method_title ); ?></p>
                <p><strong>运费总额:</strong><?php echo wc_price( $shipping_total ); ?></p>
                <?php
                // 显示运费税费(如果存在)
                $shipping_tax = WC()->cart->get_shipping_tax();
                if ( $shipping_tax > 0 ) {
                    echo '<p><strong>运费税费:</strong>' . wc_price( $shipping_tax ) . '</p>';
                }
                ?>
            </div>
            <?php
        } else {
            // 用户未选择配送方式时的提示
            ?>
            <div class="shipping-notice" style="margin: 1em 0; color: #666;">
                <p>请先选择配送方式以查看运费详情</p>
            </div>
            <?php
        }
    }
}

代码说明:

  1. 钩子适配:直接绑定到你指定的woocommerce_review_order_before_payment位置,确保在付款模块前显示运费信息
  2. 数据获取:通过WC()->cart获取实时运费总额、税费,通过会话数据获取用户选中的配送方式并解析其名称
  3. 状态判断:区分用户已选/未选配送方式的场景,给出对应提示或详情展示
  4. 样式兼容:添加基础内联样式,可根据主题需求自定义CSS类调整外观

将上述代码添加到主题的functions.php文件或自定义插件中即可生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:50:39