简体   繁体   中英

WooCommerce cart discount: one item free based on item quantity

I'm trying to implement a custom discount rule to the cart. Basically there is WooCommerce and the site is selling t-shirts. There is a current promotion that if you buy 3 t-shirts, you have to pay only for 2 and the one with the lowest price you get for free.

I created a custom function using the hook woocommerce_cart_calculate_fees and so far it's working.

Here is my code:

add_action( 'woocommerce_cart_calculate_fees', 'iom_add_custom_discount', 10, 1 );
function iom_add_custom_discount( $wc_cart ){
    $discount = 0;
    $product_ids = array();
    $item_prices = array();
    $in_cart = true;

    foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
        $cart_product = $cart_item['data'];
        if ( has_term( 'detski-bodita', 'product_cat', $cart_product->get_id() ) ) {
            $in_cart = true;
        }else {
            $product_ids[] = $cart_product->get_id();
            $item_prices[$cart_product->get_id()] = $cart_product->get_price();
        }

    }

    if( $in_cart ) {
        $count_ids = count($product_ids);
        asort( $item_prices ); //Sort the prices from lowest to highest
        
        $count = 0;
        if( $count_ids == 3 ) { 
           foreach( $item_prices as $id => $price ) {
                if( $count >= 1 ) {
                    break;
                }
                //$product = wc_get_product( $id );
                //$price = $product->get_price();
                $discount -= ($price * 100) / 100;
                $count++;
           }
       }

    } 

    if( $discount != 0 ){
        $wc_cart->add_fee( 'Отстъпка', $discount, true  );
        # Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
    }
}

The discount is displayed and applied. But, it appears that it only works if I have 3 different products in the cart. If I have 1 product with quantity 2 and 1 product with quantity 1 it's not working.

How to tweak the function to make it work for item quantity count instead?

Here is the screenshot of the cart page:

在此处输入图像描述


Edit:

Explanation about product categories in the discount:

The discount should only be applied if 3 items from the same category are in the cart.

For example, the categories are t-shirts and hoodies. If I have 3 t-shirts in my cart, the discount should be applied. If I have 2 t-shirts and 1 hoodie the discount should not be applied.

After some testing and stuff, I managed to make it work as described. Here is the code:

add_action( 'woocommerce_cart_calculate_fees', 'iom_add_custom_discount', 10, 1 );
function iom_add_custom_discount( $wc_cart ){
    $discount = 0;
    $product_ids = array();
    $item_prices = array();
    $in_cart = false;

    foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
        $cart_product = $cart_item['data'];
        // var_dump($cart_product->get_parent_id());
        // var_dump(has_term( 'detski-bodita', 'product_cat', $cart_product->get_parent_id() ));

        // here we check if the products in the cart are in category 'detski-bodita'.
        // since these are variation products, we check if their parents have the category.
        // if they do we add them the $in_cart boolean to true.
        if ( has_term( 'detski-bodita', 'product_cat', $cart_product->get_parent_id() ) ) {
            $in_cart = true;
            // var_dump($cart_product);
            $product_ids[] = $cart_product->get_id();
            $item_prices[$cart_product->get_id()] = $cart_product->get_price(); 
        } else {
            $product_ids[] = $cart_product->get_id();
            $item_prices[$cart_product->get_id()] = $cart_product->get_price(); 
        }

    }

    // here we chek if we have products with $in_cart boolean to true 
    // and if they are in category 'detski-bodita'
    if( $in_cart && has_term( 'detski-bodita', 'product_cat', $cart_product->get_parent_id() )) {
        // var_dump($item_prices);
        $count_ids = count($product_ids); // We count the items we have
        asort( $item_prices ); //Sort the prices from lowest to highest
        

        $count = 0; // we add another counter for the products that will be discounted.
        // here we check if the minimum amount of products is met for the discount.
        if( $count_ids >= 3 ) { 
            foreach( $item_prices as $id => $price ) {
                if( $count >= 1 ) {
                // var_dump($price)
                    break;
                }
                //$product = wc_get_product( $id );
                //$price = $product->get_price();
                $discount -= ($price * 100) / 100; // this is the discount that we apply - 100%
                $count++; // increase the counter in order to stop after the max amount of discounted products
           }
       }

    }

    if( $discount != 0 ){
        $wc_cart->add_fee( 'Отстъпка', $discount, true  );
        # Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
    }
}

I'm still testing it, but so far it's working. Maybe the main problem before was that I didn't considered that the products are with variations and the category parsing was failing. When I added 'get_parent_id()' I was able to get the correct category. Now I just have to figure out the problem with the quantity. For example if one product from the category have quantity of 2 and one have quantity of 1 or if one product from the category have quantity of 3 or more. Would really appreciate some help on it or any ideas for improvement. :) Thanks:)

EDIT: It appears that if I select 3 products from the right category and 1 product from any other, the discount is applied. But when I remove one of the items that are from the right category, the discount is still applied, when it shouldn't. :( How could I fix this? Thanks:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM