You need to enable JavaScript to run this app. 如何在WooCommerce订单邮件及我的账户订单页新增自定义应付总金额行
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce订单邮件及我的账户订单页新增自定义应付总金额行

WooCommerce 自定义总金额多场景适配方案

1. 重构通用可复用函数

首先把原有仅支持购物车场景的函数改造为兼容购物车、订单两种场景的通用函数,避免逻辑重复:

function get_custom_total_row( $order = null ) {
    // 判断场景:有订单对象用订单数据,无则用购物车数据
    if ( $order && is_a( $order, 'WC_Order' ) ) {
        $subtotal = $order->get_subtotal();
        $total = $order->get_total();
        $currency = $order->get_currency();
        // 适配邮件/订单页的表格样式
        $th_class = 'class="td" scope="row"';
        $td_class = 'class="td"';
        $text_align = is_rtl() ? 'left' : 'right';
        $style = "style=\"text-align:{$text_align};\"";
    } else {
        $subtotal = WC()->cart->subtotal;
        $total = WC()->cart->total;
        $currency = get_woocommerce_currency();
        $th_class = '';
        $td_class = 'data-title="total-to-pay"';
        $style = '';
    }
    // 计算逻辑和原有保持一致
    $total_to_pay = $total - $subtotal;
    
    // 输出表格行
    return '<tr class="cart-total-to-pay">
        <th ' . $th_class . ' ' . $style . '>' . __( 'Total (to pay)', 'woocommerce' ) . '</th>
        <td ' . $td_class . ' ' . $style . '>' . wc_price( $total_to_pay, array( 'currency' => $currency ) ) . '</td>
    </tr>';
}

// 原有购物车、结算页的输出逻辑适配
function display_custom_total() {
    echo get_custom_total_row();
}
add_action( 'woocommerce_cart_totals_after_order_total', 'display_custom_total', 20 );
add_action( 'woocommerce_review_order_after_order_total', 'display_custom_total', 20 );

2. 一键添加到订单邮件、我的账户-订单详情页

不需要修改邮件模板,直接使用WooCommerce内置的woocommerce_get_order_item_totals过滤钩子,即可把自定义行插入到总计行的指定位置,该钩子在邮件、我的账户订单详情页会同时生效:

add_filter( 'woocommerce_get_order_item_totals', 'add_custom_total_to_order_totals', 10, 3 );
function add_custom_total_to_order_totals( $total_rows, $order, $tax_display ) {
    $new_rows = array();
    // 遍历原有总计行,把自定义行插入到订单总金额行之后
    foreach ( $total_rows as $key => $row ) {
        $new_rows[ $key ] = $row;
        if ( 'order_total' === $key ) {
            // 插入自定义行,计算逻辑和全局保持一致
            $new_rows['custom_total_to_pay'] = array(
                'label' => __( 'Total (to pay)', 'woocommerce' ),
                'value' => wc_price( $order->get_total() - $order->get_subtotal(), array( 'currency' => $order->get_currency() ) )
            );
        }
    }
    return $new_rows;
}

可选:手动修改邮件模板的实现方式

如果你确实需要直接修改email-order-details.php模板,只需要在你提到的总计行tr代码之后,添加一行调用通用函数的代码即可:

<?php echo get_custom_total_row( $order ); ?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 21:36:05