Conditional progressive percentage discount based on cart item count in Woocommerce

后端 未结 1 365
小鲜肉
小鲜肉 2020-12-11 09:58

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 a

相关标签:
1条回答
  • 2020-12-11 10:44

    Update - October 2018 (code improved)

    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.

    The calculation:
    — The item count is 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)
    — We use the discounted subtotal (to avoid adding multiple collapsing discounts made by coupons)

    The code:

    add_action( 'woocommerce_cart_calculate_fees', 'cart_progressive_discount', 50, 1 );
    function cart_progressive_discount( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // For 1 item (quantity 1) we EXIT;
        if( $cart->get_cart_contents_count() == 1 )
            return;
    
        ## ------ Settings below ------- ##
    
        $percent = 5; // Percent rate: Progressive discount by steps of 5%
        $max_percentage = 50; // 50% (so for 10 items as 5 x 10 = 50)
        $discount_text = __( 'Quantity discount', 'woocommerce' ); // Discount Text
    
        ## ----- ----- ----- ----- ----- ##
    
        $cart_items_count = $cart->get_cart_contents_count();
        $cart_lines_total = $cart->get_subtotal() - $cart->get_discount_total();
    
        // Dynamic percentage calculation
        $percentage = $percent * ($cart_items_count - 1);
    
        // Progressive discount from 5% to 45% (Between 2 and 10 items)
        if( $percentage < $max_percentage ) {
            $discount_text .=  ' (' . $percentage . '%)';
            $discount = $cart_lines_total * $percentage / 100;
            $cart->add_fee( $discount_text, -$discount );
        }
        // Fixed discount at 50% (11 items and more)
        else {
            $discount_text .=  ' (' . $max_percentage . '%)';
            $discount = $cart_lines_total * $max_percentage / 100;
            $cart->add_fee( $discount_text, -$discount );
        }
    }
    

    Code goes in function.php file of your active child theme. Tested and works.

    When using FEE API for discounts (a negative fee), taxes are always applied.


    References:

    • WooCommerce - Adding shipping fee for free user plan
    • WooCommerce - Make a set of coupons adding a fixed fee to an order
    • WooCommerce class - WC_Cart - add_fee() method
    0 讨论(0)
提交回复
热议问题