Skip to content

Instantly share code, notes, and snippets.

@dr5hn
Created October 15, 2017 09:52
Show Gist options
  • Save dr5hn/ff6afc16b50ed690da61558f0f1b63cb to your computer and use it in GitHub Desktop.
Save dr5hn/ff6afc16b50ed690da61558f0f1b63cb to your computer and use it in GitHub Desktop.
How to show subtotal after applying and deducting coupon discount.
<?php
/**
* Show the cart subtotal after coupon discount -- By Darshan Gada
* @uses coupon_discount()
*/
function update_woocommerce_cart_subtotal( $cart_subtotal, $compound, $obj ){
$t = 0;
foreach ( $obj->cart_contents as $key => $product ) :
$product_price = $product['line_total'];
foreach ( WC()->cart->get_coupons('order') as $code => $coupon ) :
if( in_array( $product['product_id'], $coupon->product_ids )
|| in_array( $coupon->discount_type, array( 'percent_cart', 'fixed_cart' ) ) ):
$product_price = coupon_discount( $product['line_total'], $coupon->discount_type, $coupon->amount );
endif;
endforeach;
$t += $product_price;
endforeach;
return ( $t > 0 ) ? sprintf( '%s', wc_price( $t ) ) : $cart_subtotal ;
}
function coupon_discount( $price, $type, $amount ){
switch( $type ){
case 'percent_product':
$newprice = $price * ( 1 - $amount/100 );
break;
case 'fixed_product':
$newprice = $price - $amount;
break;
case 'percent_cart':
$newprice = $price * ( 1 - $amount/100 );
break;
case 'fixed_cart':
$newprice = $price - $amount;
break;
default:
$newprice = $price;
}
return $newprice;
}
add_filter( 'woocommerce_cart_subtotal', 'update_woocommerce_cart_subtotal', 99, 3 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment