Last active
September 3, 2025 11:36
-
-
Save kartikparmar/84e4b2c1d57723cde923153328802fca to your computer and use it in GitHub Desktop.
Apply discount on the other nights
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| add_action('woocommerce_cart_calculate_fees', 'discount_after_first_night', 20, 1); | |
| function discount_after_first_night($cart) { | |
| if (is_admin() && !defined('DOING_AJAX')) return; | |
| $total_discount = 0; | |
| foreach ($cart->get_cart() as $cart_item) { | |
| // Check if the product has booking data | |
| if (!isset($cart_item['bkap_booking'])) continue; | |
| $booking = $cart_item['bkap_booking'][0]; | |
| // Get check-in and check-out dates | |
| $check_in = isset($booking['hidden_date']) ? $booking['hidden_date'] : ''; | |
| $check_out = isset($booking['hidden_date_checkout']) ? $booking['hidden_date_checkout'] : ''; | |
| if (!$check_in || !$check_out) continue; | |
| // Convert dates to timestamps | |
| $start = strtotime($check_in); | |
| $end = strtotime($check_out); | |
| // Calculate number of nights | |
| $nights = ($end - $start) / (60 * 60 * 24); | |
| // Skip if only 1 night (no discount) | |
| if ($nights < 2) continue; | |
| // Get price per night (assumed to be the product price) | |
| $price_per_night = floatval($cart_item['data']->get_price()) / $nights; | |
| // Calculate number of discounted nights (starting from night 2) | |
| $discounted_nights = $nights - 1; | |
| // Calculate 30% discount for each additional night | |
| $additional_night_price = $discounted_nights * $price_per_night; | |
| $discount = $discounted_nights * $price_per_night * 0.30; | |
| $total_discount += $discount; | |
| } | |
| // Apply discount to cart if any | |
| if ($total_discount > 0) { | |
| $cart->add_fee(__('Discount after first night', 'your-theme-textdomain'), -$total_discount); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment