Conditionally change PRODUCT subtotal
-
Hi guys,
I have an issue of conditionally setting product subtotal.The task is if 5 products are bought of the same category, 6th added product gets a 100% discount.
I’ve done it using this code:
add_action( 'woocommerce_before_calculate_totals', 'make_nth_cat_item_in_cart_free' ); function make_nth_cat_item_in_cart_free( $cart_object ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return; // it is our quantity of products in specific product category $quantity = 0; // Nth category product for free $numberOfCategoryProductForFree = 6; $categories = array('category_1'); foreach ( $cart_object->get_cart() as $hash => $value ) { // If product categories is found if ( has_term( $categories, 'product_cat', $value['product_id'] ) ) { // if yes, count its quantity $quantity += $value['quantity']; // Save nth product in category id if ($quantity == $numberOfCategoryProductForFree) { $freeProductId = $value['data']->get_id(); } } } // change prices if( $freeProductId && $quantity >= $numberOfCategoryProductForFree ) { foreach ( $cart_object->get_cart() as $hash => $value ) { if ($value['data']->get_id() == $freeProductId) { if ($value['quantity'] > 1) { // HERE IS THE PROBLEM } else { $newprice = 0; } $value['data']->set_price( $newprice ); break; } } } }The problem is when product quantity is > 1 i am unable to set product price to 0, or I do not want to change product price to other amount, I just want to display the product subtotal for 1 quantity less of a price.
Please let me know how can I:
TEST CASES:
1) make sure if 6 quantities of a same product are added to cart, product subtotal is displayed only for 5 product price.
2) make sure if 3 quantities of one product is added and 3 quantities of other product is added I need to make sure second product subtotal would be a price of 2.
The topic ‘Conditionally change PRODUCT subtotal’ is closed to new replies.