I would like to restrict other products from being added in the cart if a specific product in a category id 154 is already in the cart. How to change the product id to category id in the below code?
function example_cart_filtering( $passed_validation, $product_id ) {
// ID of the trial product
// list of products
$trial_product_id = 10383;
//$category = '154';
// If cart is empty, no need for additional validation.
if ( WC()->cart->is_empty() ) {
return $passed_validation;
}
// If trial product is being added to cart, existing products should be removed.
if ( $trial_product_id === $product_id ) {
$notice = sprintf(
// Translators: Placeholder is for cart url.
__( 'Hampers can not be purchased with other products. Please empty your <a href="%s">existing cart</a>.' ),
esc_url( wc_get_cart_url() )
);
wc_add_notice( $notice, 'notice' );
return false;
}
// If trial product is in cart, additional products should not be added.
$products = WC()->cart->get_cart_contents();
foreach ( $products as $product => $values ) {
$product_id = $values['data']->get_id();
if ( $trial_product_id === $product_id ) {
$notice = sprintf(
// Translators: Placeholder is for cart url.
__( 'Hampers can not be ordered with other items.<br> Please remove the Hamper products from <a href="%s">your cart</a> if you wish to make other purchases.' ),
esc_url( wc_get_cart_url() )
);
wc_add_notice( $notice, 'notice' );
return false;
}
}
// Trial Product is not in cart or being added.
return $passed_validation;
}
add_filter( 'woocommerce_add_to_cart_validation', 'example_cart_filtering', 100, 2 );