Updated: Here are the changes that are required to "auto add a product in cart except for specific defined product categories (not removing the auto added product if mixed categories are in cart):
add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_except_for_product_category', 10, 1 );
function auto_add_item_except_for_product_category( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Settings
$except_terms = array('t-shirts'); // Required product category(ies)
$auto_added_id = 70; // Specific product to be added automatically
$except_found = false;
$others_found = false;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Check for product category
if( has_term( $except_terms, 'product_cat', $cart_item['product_id'] ) ) {
$except_found = true;
} else {
$others_found = true;
}
// Check if specific product is already auto added
if( $cart_item['data']->get_id() == $auto_added_id ) {
$auto_added_item_key = $cart_item_key; // keep cart item key
}
}
// If auto added product is in cart with at least an item from a the defined product category only
if ( isset($auto_added_item_key) && $except_found && ! $others_found ) {
$cart->remove_cart_item( $auto_added_item_key ); // Remove specific product
}
// If there is at least an item from others product categories and the specific product is not in cart
elseif ( ! isset($auto_added_item_key) && ! $except_found ) {
$cart->add_to_cart( $auto_added_id ); // Add specific product
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Based on: Auto add a product for cart item from specific product categories in WooCommerce
if ( isset($saved_item_key) && $matched_category )
(! before $matched_category removed) andelseif ( ! isset($saved_item_key) && ! $matched_category )
(! before $matched_category added.) Can you try and see what result you get with that? – CBroe