John Davidson

php - Woocommerce coupon discount when item price is less than the discount amount

0 comments
Message:


From my understanding of how woocommerce_coupon_get_discount_amount works. The discount is calculated as to how much it would discount each item in the cart. For example, if you had 4 items in the cart at $10, and you were to discount one item to be free. Then you would return $2.50 to each product in the cart. Thus discounting one of the products by 100%.


However, let's say that you had a product in the cart that was $1, then instead of discounting $10, the discount applied would be $8.50. Making the discount incorrect.


For this above example the coupon would be calculated as so:


add_filter('woocommerce_coupon_get_discount_amount', 'mb_wcchpi_cpn_disc', 10, 5);
function mb_wcchpi_cpn_disc($discount, $discounting_amount, $cart_item, $single, $coupon)
{
//IF CUSTOM COUPON TYPE
if ($coupon->type == 'most_expensive_coupon') {
//Gets the most expensive item in the cart
$mostExpensiveItem = FindMaxPricedItem($multiple_products);

//Get the price of the most expensive item in the cart
$maxPrice = $mostExpensiveItem['price'];

//GET THE COUPON DISCOUNT AMOUNT
$amt = floatval($coupon->amount);

//GET THE DISCOUNT AMOUNT
$discount = ($amt / 100) * $maxPrice;

//GET THE ITEMS IN THE CART
$itemCount = WC()->cart->cart_contents_count;

//DISTRIBUTE EQUALLY ACROSS ALL ITEMS IN CART
$discount = $discount / $itemCount;
}

return $discount;

}


How would one handle the edge case of having an item in the cart that is less than the discount amount? Is there a different action than woocommerce_coupon_get_discount_amount to be used for applying a coupon to the cart total instead of per item? Is there a different formula I should be using to come up with the discount?



My Answer:
>is_type('custom')) {
//IF ITEM PRICE IS LESS THAN DISCOUNT AMOUNT
if ($cart_item['data']->get_price() < $coupon->get_amount()) {
//CALCULATE DISCOUNT BASED ON ITEM PRICE
$discount = $cart_item['data']->get_price();
}
}
return $discount;
}

This code snippet checks if the coupon type is 'custom' and if the item price is less than the discount amount specified in the coupon. If it is, then it calculates the discount based on the item price instead of the discount amount. This ensures that the discount is applied correctly for items with prices lower than the discount amount.

Rate this post

3 of 5 based on 6866 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us