Site icon Qaisar Satti's Blogs

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:

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 );
    }
}

 

Exit mobile version