Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In WooCommerce, how do I set a cart discount based on the total number of items in the cart?

For example:

  • 1 to 4 items - no discount
  • 5 to 10 items - 5%
  • 11 to 15 items - 10%
  • 16 to 20 items - 15%
  • 21 to 25 items - 20%
  • 26 to 30 items - 25%

I've search internet but not found any solution or plugins available.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
368 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use a negative cart fee to get a discount. Then you will add your conditions & calculations to a acustom function hooked in woocommerce_cart_calculate_fees action hook, this way:

## Tested and works on WooCommerce 2.6.x and 3.0+
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 <= 4 )
        $percent = 0;
    elseif( $cart_item_count >= 5 && $cart_item_count <= 10 )
        $percent = 5;
    elseif( $cart_item_count > 10 && $cart_item_count <= 15 )
        $percent = 10;
    elseif( $cart_item_count > 15 && $cart_item_count <= 20 )
        $percent = 15;
    elseif( $cart_item_count > 20 && $cart_item_count <= 25 )
        $percent = 20;
    elseif( $cart_item_count > 25 )
        $percent = 25;


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

    ## ----  APPLYING CALCULATED DISCOUNT TAXABLE ---- ##
    if( $percent > 0 )
        $cart_object->add_fee( __( "Quantity discount $percent%", "woocommerce" ), $discount, true);
}

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

Tested and works on WooCommerce 2.6.x and 3.0+


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...