Untitled

 avatar
webwizards
plain_text
9 months ago
2.1 kB
14
Indexable
add_filter('woocommerce_coupon_get_discount_amount', 'b2bking_best_price_coupon_logic', 10, 5);
function b2bking_best_price_coupon_logic($discount, $discounting_amount, $cart_item, $single, $coupon) {
    
    // Get the product
    $product = $cart_item['data'];
    
    // Check if product has a sale price
    $regular_price = (float) $product->get_regular_price();
    $sale_price = (float) $product->get_sale_price();
    
    if (empty($sale_price) || $sale_price >= $regular_price) {
        // No sale price, use default coupon behavior
        return $discount;
    }
    
    // Calculate the discount from sale
    $sale_discount_amount = $regular_price - $sale_price;
    
    // Calculate what the coupon discount would be from regular price
    $coupon_discount_amount = 0;
    
    if ($coupon->get_discount_type() === 'percent') {
        // Percentage coupon
        $coupon_percent = $coupon->get_amount();
        $coupon_discount_amount = ($regular_price * $coupon_percent) / 100;
    } elseif ($coupon->get_discount_type() === 'fixed_product' || $coupon->get_discount_type() === 'fixed_cart') {
        // Fixed amount coupon
        $coupon_discount_amount = $coupon->get_amount();
    } else {
        // Other coupon types, use default behavior
        return $discount;
    }
    
    // Apply the BEST discount (larger discount wins)
    if ($coupon_discount_amount > $sale_discount_amount) {
        // Coupon is better - apply additional discount on top of sale
        // The coupon should bring the price from sale_price down to (regular_price - coupon_discount)
        // So the additional discount needed is: coupon_discount_amount - sale_discount_amount
        $additional_discount = $coupon_discount_amount - $sale_discount_amount;
        
        // Adjust for quantity if not single
        if (!$single) {
            $additional_discount = $additional_discount * $cart_item['quantity'];
        }
        
        return $additional_discount;
    } else {
        // Sale price is better - don't apply coupon at all
        return 0;
    }
}
Editor is loading...
Leave a Comment