This WooCommerce customization is similar to targeted promotions. In online shops, it is common to find some high values items to go out of trend which is moving slowly. So in such scenarios it is a strategic move to target these products with this kind of BOGO deal. This will benefit in many aspects from increasing overal sales volume to potentially attracting new customers.
Solution: Offer a BOGO (Buy One Get One) Discount on the Highest Priced Item in the WooCommerce
This code offers a discount based on the highest-priced item in the WooCommerce cart , applies it as a discount fee 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); } }
This to the shop owners who are running or planning to run BOGO offers on their WooCommerce store…
BOGO deals are great for increasing your sales, but have you thought about which offers are bringing you more revenue and which offers are not performing that great?
Don’t just set a BOGO deal, track the revenue generated by your deals in real-time with the Flexi BOGO for WooCommerce plugin.
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.
If you are interested to explore similar customizations, then consider targeting the least expensive item and apply BOGO buy one get one discounts to cart cheapest item during a promotion in WooCommerce.