I am using filter woocommerce_coupon_get_discount_amount filter hook to recalculate coupon discount based on product attributes. Code calculates the result I want, but the returned value is applied at the cart to each line item, I want it to apply as a single discount to the whole cart.
For example, if I calculate and return $100, but there are 4 items in the cart, the discount on the cart becomes $400.
Am I using the correct filter for cart discount? Is there a better way to apply the discount only to items with certain product attributes?
The discount should only apply to items with size of 'Low-Res'.
/* apply 'free download' coupon to 'Low-Res' download items only */
/* by calculating their qty and price and updating the discount */
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 1 );
function filter_woocommerce_coupon_get_discount_amount( $discounting_amount ) {
$discount_is_for = 'Low-Res';
$coupon_code = 'free download';
$discounting_amount = 0;
$cart_coupons = WC()->cart->get_coupons();
// check to see if the 'free download' coupon has been added
foreach ($cart_coupons as $coupon) {
if ($coupon->code == $coupon_code) {
foreach ( WC()->cart->get_cart() as $cart_item ) {
// check to see if it's a Low-Res download
$product = $cart_item['data'];
$attributes = $product->get_attributes();
if ($product->get_attribute( 'pa_size' ) == $discount_is_for) {
// gets the cart item quantity
$quantity = $cart_item['quantity'];
// gets the cart item subtotal
$line_subtotal = $cart_item['line_subtotal'];
$line_subtotal_tax = $cart_item['line_subtotal_tax'];
// gets the cart item total
$line_total = $cart_item['line_total'];
$line_tax = $cart_item['line_tax'];
// unit price of the product
$item_price = $line_subtotal / $quantity;
$item_tax = $line_subtotal_tax / $quantity;
$discounting_amount += $cart_item['quantity'] * ($item_price + $item_tax);
}
}
}
}
return $discounting_amount;
}