If there are specific high-value items that aren’t moving quickly, then this kind of BOGO deal will motivate customers to purchase high-priced items. This code offers a discount in the cart by applying a fee based on the price of the highest-priced item when there is more than one item in the cart.
add_action('woocommerce_cart_calculate_fees', 'ts_apply_discount_based_on_highest_price'); function ts_apply_discount_based_on_highest_price() { if (is_admin() && !defined('DOING_AJAX')) return; $items_prices = []; $items_count = 0; // Loop through cart items foreach (WC()->cart->get_cart() as $key => $item) { // Get the cart item price (the product price) $price = wc_prices_include_tax() ? wc_get_price_including_tax($item['data']) : wc_get_price_excluding_tax($item['data']); if ($price > 0) { $items_prices[$key] = $price; $items_count += $item['quantity']; } } // Only when there is more than one item in cart if ($items_count > 1) { arsort($items_prices); // Sorting prices from highest to lowest $highest_item_key = key($items_prices); // Get current cart item key with the highest price // Calculate the discount as the price of the highest item $discount = $items_prices[$highest_item_key]; // Apply the discount as a fee to the cart WC()->cart->add_fee('Highest Price Discount', -$discount, true); } }
Output
The output shows that as the number of items in the cart increases, the code iterates through each item, identifies the key of the highest-priced items, and then applies the corresponding highest price as the discount amount.
Note: The discount doesn’t get applied when there is only one item present in the cart.
Alternatively, you can also apply BOGO buy one get one discounts to cart cheapest item during a promotion in WooCommerce.