3

I am trying to add Coupon Discount on cart items and I am able to do that but the issue is I don't want to stick out the item which doesn't have coupon discount items.

Currently, It looks like this way

enter image description here

But I Want it to look like this way.

enter image description here

In Simple words, I want the stick out only the cart item which has discount/Coupon discount applied and other items price stay same.

Here is my current code in the function.php

add_filter( 'woocommerce_cart_item_subtotal', 'show_coupon_item_subtotal_discount', 99, 3 );
function show_coupon_item_subtotal_discount( $subtotal, $cart_item, $cart_item_key ){
global $woocommerce;
if ( $woocommerce->cart->has_discount( $coupon_code )) {
$newsubtotal = wc_price( woo_type_of_discount( $cart_item['line_total'], $coupon->discount_type, $coupon->amount ) );
$subtotal = sprintf( '<s>%s</s> %s', $subtotal, $newsubtotal ); 
}
return $subtotal;

}


function woo_type_of_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;
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Ashfaq Ahmed
  • 53
  • 1
  • 6

1 Answers1

3

In cart there are already some related features that help on coupon discounts and that will simplify what you are trying to do. There is 2 cart item totals available:

  • 'line_subtotal' is the non discounted cart item line total
  • 'line_total' is the discounted cart item line total

So there is no need of an external function and also to detect if a coupon is applied or not. So the functional code is going to be very compact to get the desired display:

add_filter( 'woocommerce_cart_item_subtotal', 'show_coupon_item_subtotal_discount', 100, 3 );
function show_coupon_item_subtotal_discount( $subtotal, $cart_item, $cart_item_key ){
    if( $cart_item['line_subtotal'] !== $cart_item['line_total'] ) {
        $subtotal = sprintf( '<del>%s</del> <ins>%s</ins>',  wc_price($cart_item['line_subtotal']), wc_price($cart_item['line_total']) );
    }
    return $subtotal;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

enter image description here

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • LoicTheAztec, You are a super start. Thank you so much for helping me. I was stuck last few days but you make my day. – Ashfaq Ahmed Dec 10 '18 at 06:49
  • hey LoicTheAztec, as i can see in your answer, you have definitely changed the price of single item subtotal but if you look at cart totals, they are still calculating from product original price. So can you help into it. as i am also stuck – Hritik Pandey Feb 07 '20 at 13:17
  • maybe a typo there? %s should be %s – Nat Feb 08 '20 at 09:27