Kasper Tang Højriis Kasper Tang Højriis - 2 months ago 13
PHP Question

WooCommerce - Conditional Progressive Discount based on number of items in cart

I would like to have a conditional progressive discount based on number of items in cart. After you added 2 products to the cart, you get a discount. More products you add and more discount you get.

For example:


  • 1 product – full price (No Discount)

  • 2 products – full price with 10% discount of the combined price

  • 3 products – full price with 15% discount of the combined price

  • 4 products – full price with 20% discount of the combined price

  • And so on …



I have search over internet without any success. When searching about discounts I just fall on WooCommerce coupon feature or I get some old wrong code…

Any idea? How can I do it?

Is it possible?

Thanks.

Answer

Yes its possible to use a trick, to achieve this. Normally for discounts on cart we use in WooCommerce coupons. Here coupons are not appropriated. I will use here a negative conditional fee, that becomes a discount.

So Here is this code:

/* The calculation:
 *  — The count => Based on quantity by item and total of items in cart
 *  — The percent is 0.05 (5%) and  it grows with each additional item (as you asked)
 *  — I add the subtotal of each item line to get the total sum…
 */

function cart_progressive_discount() {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $cart_count = 0;
    $cart_lines_total = 0;

    foreach(WC()->cart->get_cart() as $item_key => $cart_item){
        // Adds the quantity of each item to the count
        $cart_count = $cart_count + $cart_item["quantity"];
        // Adds The items subtotal to total
        $cart_lines_total += $cart_item["line_total"];
    }

    // percent is 5%
    $percent = -0.05;
    // We fix the discount max to 50% (-0.05 * 10)
    $cart_count_max = 10;

    // Discount calculations:
    $discount = $percent * $cart_count * $cart_lines_total;
    $discount2 = $percent * $cart_count_max * $cart_lines_total;
    $discount_text = __( 'Quantity discount', 'woocommerce' );

    // For 0 or 1 item
    if( $cart_count < 2 ) {
        return;
    }
    // Between 2 and 9 items, progressive incremental discount based on item quantity (From 10% to 45%)
    elseif( $cart_count > 1 && $cart_count < 10) {
        WC()->cart->add_fee( $discount_text, $discount, false );
    }
    // Up to 9 items (Fixed discount at 50%)
    else {
        WC()->cart->add_fee( $discount_text, $discount2, false );
    }
}
add_action( 'woocommerce_cart_calculate_fees','cart_progressive_discount' );

Naturally, this goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Here the discount is not taxable, see in the last reference below.


References:

Comments