Search code examples
phpwordpresswoocommercecartdiscount

Woocommerce percentage discount per item based on quantity


Based on WooCommerce Cart Quantity Base Discount answer code, I apply a discount from xx products on shopping cart with the following:

  add_action( 'woocommerce_cart_calculate_fees','wc_cart_quantity_discount', 10, 1 );
function wc_cart_quantity_discount( $cart_object ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    ## -------------- DEFINIG VARIABLES ------------- ##
    $discount = 0;
    $cart_item_count = $cart_object->get_cart_contents_count();
    $cart_total_excl_tax = $cart_object->subtotal_ex_tax;

    ## ----------- CONDITIONAL PERCENTAGE ----------- ##
    if( $cart_item_count <= 17 )
        $percent = 0;
    elseif( $cart_item_count >= 18 && $cart_item_count <= 120 )
        $percent = 10;



    ## ------------------ CALCULATION ---------------- ##
    $discount -= ($cart_total_excl_tax / 100) * $percent;

    ## ----  APPLYING CALCULATED DISCOUNT TAXABLE ---- ##
    if( $percent > 0 )
        $cart_object->add_fee( __( 'Remise sur la quantité 10%', 'woocommerce' ), $discount, true);
}

But I would like to manage the discount from quantity for each product.

Do you have any tips for that?


Solution

  • The following will make a percentage discount based on item quantity:

    add_action( 'woocommerce_cart_calculate_fees','cart_quantity_discount' );
    function cart_quantity_discount( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $discount = 0; // Initializing
        $percent  = 10;  // Percentage
        
        // Loop through cat items
        foreach ( $cart->get_cart() as $cart_item ) {
            $subtotal = $cart_item['line_total'];
            
            // Calculation by Item based on quantity
            if( $cart_item['quantity'] > 17 ) {
                $discount += $cart_item['line_total'] * $percent / 100;
            }
        }
        
        if( $discount > 0 ) {
            $cart->add_fee( __( "Item quantity discount", "woocommerce" ), -$discount, true );
        }   
    }
    

    Code goes on functions.php file of your active child theme (or active theme). It should works.