I am trying to achieve the following:
How to make if Product 2 is in cart, make Product 1 = $0 and all added products from category Books $0?
My idea is if a customer buys a certain product this makes free all products of a product category.
So far I got this, but is it is not working and is making all of the products in cart to $0
:
add_action( 'woocommerce_before_calculate_totals', 'change_price_if_6245_in_cart' );
function change_price_if_6245_in_cart( $cart_object ) {
if (woo_in_cartbooks (6245) ) {
// set our flag to be false until we find a product in that category
$cat_check = false;
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
// replace 'books' with your category's slug
if ( has_term( 'books', 'product_cat', $product->id ) ) {
$cat_check = true;
// break because we only need one "true" to matter here
break;
}
}
// if a product in the cart is in our category, do something
if ( $cat_check ) {
// we have the category, do what we want
foreach ( $cart_object->get_cart() as $hash => $value ) {
$value['data']->set_price( 0 );
}
}
}
Here is the correct way to make it work (code is commented):
add_action( 'woocommerce_before_calculate_totals', 'free_product_category_for_a_specific_product', 20, 1 );
function free_product_category_for_a_specific_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// HERE Below your settings
$product_category = "books"; // <= The product category (can be an ID, a slug or a name)
$specific_product_id = 6245; // <= The specific product ID
$found = false;
// 1st cart items Loop: Check for specific product
foreach ( $cart->get_cart() as $cart_item ) {
// Check for 'books' with your category's slug
if ( $cart_item['data']->get_id() == $specific_product_id ) {
$found = true;
break; // Found, we stop first loop
}
}
// If specific product is not in cart we exit
if( ! $found )
return;
// 2nd cart items Loop: check items remaining to "Books" product category when specific product is in cart
foreach ( $cart->get_cart() as $cart_item ) {
// If specific product has been found, we set price to 0 for items remaining to "Books" product category
if ( has_term( $product_category, 'product_cat', $cart_item['product_id'] ) ) {
$cart_item['data']->set_price( 0 );
}
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.