在 WooCommerce 订单电子邮件中插入不包括产品成本的自定义总计

问题描述

我正在使用以下函数向购物车和结帐页面添加自定义总计(取自 this answer 到我的问题 Insert a custom total excluding products cost row on cart and checkout totals in WooCommerce

function display_custom_total() {
    // Get (sub)total
    $subtotal = WC()->cart->subtotal;
    $total = WC()->cart->total;
    
    // Calculate
    $total_to_pay = $total - $subtotal;
    
    // The Output
    echo ' <tr class="cart-total-to-pay">
        <th>' . __( 'Total (to pay)','woocommerce' ) . '</th>
        <td data-title="total-to-pay">' . wc_price( $total_to_pay ) . '</td>
    </tr>';
}
add_action( 'woocommerce_cart_totals_after_order_total','display_custom_total',20 );
add_action( 'woocommerce_review_order_after_order_total',20 );

如何将其添加到电子邮件中的订单总计表中?

我可以使用带有钩子 woocommerce_email_after_order_table 的相同函数将其添加到电子邮件模板中,但将其添加到订单表下方而不是作为额外的行。

我知道我可以在我的子主题(特别是 email-order-details.PHP )中编辑电子邮件模板文件,但我不知道如何编辑它以将计算添加到下面的新表格行中:>

<tr>
    <th class="td" scope="row" colspan="2" style="text-align:<?PHP echo esc_attr( $text_align ); ?>; <?PHP echo ( 1 === $i ) ? 'border-top-width: 4px;' : ''; ?>"><?PHP echo wp_kses_post( $total['label'] ); ?></th>
    <td class="td" style="text-align:<?PHP echo esc_attr( $text_align ); ?>; <?PHP echo ( 1 === $i ) ? 'border-top-width: 4px;' : ''; ?>"><?PHP echo wp_kses_post( $total['value'] ); ?></td>
</tr>

我还需要将其添加到“我的帐户”>“查看订单”中的页面(如果它可以是同一功能的一部分)。

解决方法

您可以使用 woocommerce_get_order_item_totals 过滤器挂钩,这将允许您向现有表添加新行。

新行将添加到:

  • 电子邮件
  • 收到订单(感谢页面)
  • 我的账户 -> 查看订单
function filter_woocommerce_get_order_item_totals( $total_rows,$order,$tax_display ) {
    // Get (sub)total
    $subtotal = $order->get_subtotal();
    $total = $order->get_total();
    
    // Calculate
    $total_to_pay = $total - $subtotal;
    
    // Add new row
    $total_rows['total_to_pay']['label'] = __( 'Total to pay','woocommerce' );
    $total_rows['total_to_pay']['value'] = wc_price( $total_to_pay );

    return $total_rows;
}
add_filter( 'woocommerce_get_order_item_totals','filter_woocommerce_get_order_item_totals',10,3 );

相关:Insert a custom total excluding products cost row on cart and checkout totals in WooCommerce