Insert a custom total excluding products cost in WooCommerce order emails

Viewed 389

I'm using the below function to add a custom total to the cart and checkout pages (taken from this answer to my question 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', 'display_custom_total', 20 );

How can I add this to the order totals table in the emails as well?

I can add it to the email templates using the same function with the hook woocommerce_email_after_order_table but that adds it below the order table rather than as an extra row.

I know that I can edit the email template files in my child theme (particularly email-order-details.php ) but I'm not sure how to edit it to add the calculation into a new table row below this one:

<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>

I also need to add it to the page in My Account > View Order (if it can be part of the same function).

1 Answers

You can use the woocommerce_get_order_item_totals filter hook, which will allow you to add a new row to the existing tables.

The new row will be added in:

  • Emails
  • Order received (thank you page)
  • My account -> view order
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 );

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

Related