0
votes

In WooCommerce, I am applying coupons automatically, but I can't find a way to get this behaviour :

  • every time x items are in cart => apply appropriate coupon.

For example :

  • if 3 books of this author => -5€ on cart
  • if 3 books extra (same are others) of the same author => -5€ extra
  • etc. (no limit : it should works if 3000 books are ordered => -15000€ )

I use $wc->cart->add_discount($discount), but it returns "coupon already applied" as the second group of items is in the cart.

Do you know if this is possible ?

Thanks

1

1 Answers

1
votes

Instead of using coupons, you should better use a custom discount function to get this working:

add_action( 'woocommerce_cart_calculate_fees', 'cart_item_discount_by3', 10, 1 );
function cart_item_discount_by3( $cart_object ) {

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

    // initializing and set variables
    $discount = 0;
    $by3 = 3; // each 3 item quantity
    $dicount_price_by3 = 5; // amout to discount each 3 items quantity

    // Iterating through each cart item
    foreach( $cart_object->get_cart() as $cart_item ):
        // Get the item quantity
        $qty = $cart_item["quantity"];
        // starting when  quantity is upto 3
        if($qty >= $by3):
            for($j = $by3, $k = 0; $j <= $qty; $j+=$by3, $k++);
            $discount += $dicount_price_by3 * $k;
            break;
        endif;
    endforeach;

    // Adding the discount (a negative fee)
    if ($discount > 0){
        $cart_object->add_fee( __( "Discount quantity", 'woocommerce'), -$discount, true );
        # Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)

        // Displaying a custom notice (optional)
        wc_clear_notices();
        wc_add_notice( __("You get a quantity discount on some items"), 'notice');
    }
}

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

This code is tested and works.