Ad

Insert A Custom Total Excluding Products Cost Row On Cart And Checkout Totals In WooCommerce

I can add an extra row to the checkout totals table with Insert a custom total row on cart and checkout totals in Woocommerce answer code. (albeit I need to add mine at the bottom) but I can't find or figure out how to calculate the total that I need.

The total I need to add should include everything apart from the product cost (so should include shipping, VAT, fees etc.).

I can't change the product prices to zero as they're used for fee calculations.

My code attempt:

add_action( 'woocommerce_cart_totals_before_shipping', 'display_custom_total', 20 );
add_action( 'woocommerce_review_order_before_shipping', 'display_custom_total', 20 );
function display_custom_total() {
$total_to_pay = 0;
    // Do something here
 
        // The Output
        echo ' <tr class="cart-total-to-pay">
            <th>' . __( "Total to pay", "woocommerce" ) . '</th>
            <td data-title="total-to-pay">' . number_format($total_to_pay, 2) . '</td>
        </tr>';
}

How would I go about adding this to the checkout & cart page?

Ad

Answer

To display it at the bottom, use woocommerce_cart_totals_after_order_total & woocommerce_review_order_after_order_total action hook instead.

So you get:

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

Related: Insert a custom total excluding products cost in WooCommerce order emails

Ad
source: stackoverflow.com
Ad