How to Add Quantity Based Discounts in WooCommerce Programmatically

This tutorial will show you how to use custom code to automatically adjust the price per product based on the quantity in the cart.

Here’s how the discount logic works:

  • If a customer buys more than 1 and up to 10 products, the price per product drops from $80 to $75.
  • If a customer buys 10 or more products, the price per product drops to $70.

Here is the complete code snippet

// Apply Quantity-Based Discount in WooCommerce
add_action( 'woocommerce_cart_calculate_fees', 'quantity_based_discount', 10, 1 );

function quantity_based_discount( $cart ) {
    // Check if in admin and not doing AJAX
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }

    // Initialize discount amount
    $discount = 0;

    // Loop through each item in the cart
    foreach ( $cart->get_cart() as $cart_item ) {
        $qty = $cart_item['quantity'];
        $original_price = 80; // Original price per item

        // Calculate the discount based on quantity
        if ( $qty >= 1 && $qty <= 10 ) {
            $discount += $qty * ($original_price - 75); // $5 discount per item
        } elseif ( $qty > 10 ) {
            $discount += $qty * ($original_price - 70); // $10 discount per item
        }
    }

    // Apply the discount to the cart
    if ( $discount > 0 ) {
        $cart->add_fee( __( 'Quantity Discount' ), -$discount );
    }
}

 

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!