Where are you putting this code?
Probably this code is not being executed.
you should wrap everything in a function and trigger it with the wp_head hook…
<?php
add_action( 'wp_head', 'woocommerce_conditional_hook');
function woocommerce_conditional_hook(){
function check_product_in_cart() {
global $woocommerce;
$box_found = false;
$voucher_found = false;
$other_products_found = false;
//start of the loop that fetches the cart items
foreach($woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
// second level loop search, in case some items have several categories
foreach ($terms as $term) {
$_categoryid = $term->term_id;
//check if BOX product category is in card
if ( $_categoryid === 103 ) {
//category is in cart!
$box_found = true;
} elseif ( $_categoryid === 106 ) { //check if VOUCHER product category is in card
//category is in cart!
$voucher_found = true;
}else{
$other_products_found = true;
}
}
}
return array($box_found, $voucher_found, $other_products_found);
}
list($box_found, $voucher_found, $other_products_found) = check_product_in_cart();
if(!$voucher_found){
remove_action( 'woocommerce_checkout_after_customer_details', array( $wc_checkout_add_ons->admin, 'render_add_ons' ) );
add_action( 'woocommerce_after_order_notes', array( $wc_checkout_add_ons->admin, 'render_add_ons' ) );
}else{
add_action( 'woocommerce_after_order_notes', array( $wc_checkout_add_ons->admin, 'render_add_ons' ) );
}
}
?>