I have created a ‘BOGOF‘ (buy one get one free) coupon, using the normal woocommerce coupon method.
The coupon gives the user 100% percentage discount on 1 other item in the cart.
Coupon settings
General:
Discount type: Percentage discount Coupon
amount: 100
Usage limits:
- Limit usage to X items: 1
When used:
- Coupon applies 100% to a random item in the cart (default behavior, I guess)
Desired:
- It needs to take 100% off the cheapest item in the cart.
With the following code I try to achieve my goal, unfortunately without the desired result
function filter_woocommerce_coupon_get_discount_amount( $discount, $discounting_amount, $cart_item, $single, $instance ) {
$price_array = array();
foreach( $cart_item as $item ) {
echo $item->price;
if($item->price > 0){
array_push($price_array, $item->price);
}
}
$lowestPrice = min($price_array);
if( $lowestPrice < $discount ){
$discount = $lowestPrice;
}
return $discount;
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );
3
Answers
First there is a big mistake in your code as
$cart_item
variable hook argument is the current cart item but not the cart items array…The following will apply a coupon discount of 100% on the cheapest cart item (commented code):
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
If you want use your own discount not only 100% replace
return reset($items_prices);
to thereturn $discount_amount;
I made a rather small tweak to this – I noticed that if I had lots of items in my cart, it would give a 100% discount to MULTIPLE of the cheapest product. So if a user had, so 10 t-shirts at £10 each, it was giving a £100 discount. I modified this slightly below, which might help someone in the future: