WooCommerce: Add a discount based on individual items quantity

安稳与你 提交于 2019-12-06 07:55:29

问题


In my WooCommerce website I have a few products with the same price of 80$.
I want to add a Discount by the products quantity.

The logic is like that:

if (Products Quantity is 2){
   // the original product price change from 80$ to 75$ each.
}

if(Products Quantity is 3 or more){
   //the original product price change from 80$ to 70$ each.      
}

for example,

if a customer pick 2 products, the original price will be (80$ x 2) => 160$.
But after the discount, it will be: (75$ x 2) => 150$.

And…

if visitor pick 3 products, the original price will be (80$ x 3) => 240$.
But after the fee, it will be: (70$ x 3) => 210$.

Any help, please?

Thanks


回答1:


This custom hooked function should do what you expect. You can set in it your progressive discount limit based on individual item quantity.

Here is the code

## Tested and works on WooCommerce 2.6.x and 3.0+
add_action( 'woocommerce_cart_calculate_fees', 'progressive_discount_by_item_quantity', 10, 1 );
function progressive_discount_by_item_quantity( $cart_obj ) {

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

    # Progressive quantity until quantity 3 is reached (here)
    # After this quantity limit, the discount by item is fixed
    # No discount is applied when item quantity is equal to 1

    // Set HERE the progressive limit quantity discount
    $progressive_limit_qty = 3; //  <==  <==  <==  <==  <==  <==  <==  <==   <==  <==  <==

    $discount = 0;

    foreach( $cart_obj->get_cart() as $cart_item_key => $item_values ){

        $qty = $item_values['quantity'];

        if( $qty <= $progressive_limit_qty )
            $param = $qty; // Progressive
        else
            $param = $progressive_limit_qty; // Fixed

        ## Calculation ##
        $discount -=  5 * $qty * ($param - 1); 
    }

    if( $discount < 0 )
        $cart_obj->add_fee( __( 'Quantity discount' ), $discount); // Discount

}

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+



来源:https://stackoverflow.com/questions/43570692/woocommerce-add-a-discount-based-on-individual-items-quantity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!