Home > other >  How to subtract subtotal from total in WooCommerce?
How to subtract subtotal from total in WooCommerce?

Time:01-04

In WooCommerce, I'm wondering is there a simple solution to subtract the subtotal from the total without adding another fee? And thiss also appear in checkout, order (My Account) and email notifications etc.

The reason for this is that I have added custom fees / surcharges to products which is 10% reservation fee of subtotal, and I only want the surcharges to be paid first and rest offline (like collection).

For example

  • Subtotal = Purchase Price = £100
  • Reservation Fee = £10
  • Admin Fee Ontop = £5
  • Total to Pay Now = £15

So, Is there a simple way to remove the subtotal from total without having to add another line into cart totals?

This is what I tried but unfortunately getting nowhere fast and not clear on how to do this.

add_filter( 'woocommerce_calculated_total', 'custom_cart_total', 20, 2 );
function custom_cart_total( $total, $cart ) {
    return $total - $subtotal;
}

And

add_action( 'woocommerce_calculate_totals', 'custom_calculate_total', 10, 1 );
function custom_calculate_total ($total, $cart) {

    $total    = WC()->cart->get_total; 
    $subtotal = WC()->cart->subtotal();
    
    $sum_total = $total - $subtotal;
    $woocommerce->cart->set_total($sum_total);
    return $sum_total;
}

CodePudding user response:

The woocommerce_calculated_total filter hook can indeed be used, only $subtotal is undefined in your current code.

So you get:

// Allow plugins to filter the grand total, and sum the cart totals in case of modifications.
function filter_woocommerce_calculated_total( $total, $cart ) { 
    // Get subtotal
    $subtotal = $cart->get_subtotal();
    
    return $total - $subtotal;
}
add_filter( 'woocommerce_calculated_total', 'filter_woocommerce_calculated_total', 10, 2 );
  •  Tags:  
  • Related