4
votes

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;
}
1

1 Answers

4
votes

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