Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Offer a BOGO (Buy One Get One) Discount on the Highest Priced Item in the WooCommerce Cart?

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.

How to Offer a BOGO (Buy One Get One) Discount on the Highest Priced Item in the WooCommerce Cart? - Tyche Softwares

Alternatively, you can also apply BOGO buy one get one discounts to cart cheapest item during a promotion in WooCommerce.


Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x