WP SITES

3086 Coded Tutorials & 291 Plugins

Buy More than 2 Get the Cheapest Item in Cart Free

The discount only works when there’s 3 or more items in cart and applies to the cheapest item in the cart using WooCommerce.

Works with the block based cart and checkout or the old shortcode method.

add_action('woocommerce_cart_calculate_fees', 'apply_buy_2_get_3_discount');
function apply_buy_2_get_3_discount($cart) {

    if (is_admin() || !is_user_logged_in() || WC()->cart->get_cart_contents_count() < 3) {
        return;
    }

    $items = [];
    
    foreach ($cart->get_cart() as $cart_item) {
        $product_price = $cart_item['data']->get_price();
        $quantity = $cart_item['quantity'];
        
        for ($i = 0; $i < $quantity; $i++) {
            $items[] = $product_price;
        }
    }

    if (count($items) >= 3) {
        sort($items);
        $cheapest_item_price = $items[0];
        $cart->add_fee(__('Buy 2 Get 3 Discount', 'woocommerce'), -$cheapest_item_price);
    }
}

Prefer a plugin?

Try the Dynamic Cart Discounts Plugin for WooCommerce

Leave a Reply

New Plugins