There may be a situation where you don’t want certain products to be purchased together. Let’s say for example that you don’t want Product A to be purchased with Product B. If a customer has Product A in their cart then they shouldn’t be able to add Product B and vice versa. This can easily be achieved in WooCommerce with a code snippet:
function snippetpress_add_to_cart_validation( $valid, $added_product_id ) { $product_list = array( // Enter your product IDs in this array 30, 35, 39, ); foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $existing_product = $cart_item['data']; if( in_array( $existing_product->get_id(), $product_list ) && in_array( $added_product_id, $product_list ) ){ $valid = false; $added_product = wc_get_product( $added_product_id ); $added_product_name = $added_product->get_name(); $existing_product_name = $existing_product->get_name(); wc_add_notice( sprintf( __( 'You cannot add %s to the cart because %s is already in the cart.', 'woocommerce' ), $added_product_name, $existing_product_name ), 'error' ); } } return $valid; } add_filter( 'woocommerce_add_to_cart_validation', 'snippetpress_add_to_cart_validation', 10, 2 );
All you need to change in the above snippet is the product IDs in the $product_list
array. In our example we don’t want products with IDs 30 35 and 39 being purchased together – just change these to your product IDs (you can add as many or few IDs as you like).
As you can see, if a customer tries to add Product A (in our case Hoodie) to the cart when Product B (in our case Cap) is already in the cart, the action will fail and an error message will show explaining why they can’t add it to their cart.

Where to add the snippet?
The snippet should be placed at the bottom of the functions.php file of your child theme. Make sure you know what you’re doing when editing this file. Alternatively, you can use a plugin such as Code Snippets to add the custom code to your WordPress site. If you need further guidance on how to add the code, check out our post on How to Add WordPress Snippets.
Leave a Reply