I have this code, below, care of Force specific WooCommerce product to be sold in separate order and User 7uc1f3r.
I wish to add two other products to this code. The first product is simple, the other two are variable. These products have weight variations and I only want one of the weight variations to trigger the script and prevent addition to the cart with other products. So, the code would cycle through an array of product IDs (e.g. $product_id_alone_array = array("666","777","888");
), see if these are simple products or variable. If the product is simple, run the action .If the product is variable, it would need to then only select one of the variation IDs and run the actions.
I’ve worked on adding the array, determining if the product is simple or variable but cannot get the code to work. I have not posted my additional working code as it may muddy the waters.
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Product id to bought alone
$product_id_alone = 666;
// Set variable
$flag = false;
// If cart is NOT empty when a product is added
if ( ! WC()->cart->is_empty() ) {
// Generate a unique ID for the cart item
$product_cart_id = WC()->cart->generate_cart_id( $product_id_alone );
// Check if product is in the cart
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
// If product is already in cart & product ID added is not equal to product ID alone
if ( $in_cart && ( $product_id != $product_id_alone ) ) {
$flag = true;
// Product ID alone is NOT in cart & product ID added is equal to product ID alone
} elseif( ! $in_cart && ( $product_id == $product_id_alone ) ) {
$flag = true;
}
}
// True
if ( $flag ) {
// Set error message
wc_add_notice( sprintf(
__( 'Product %s must be bought separately', 'woocommerce' ),
$product_id_alone,
), 'error' );
// Passed = false
$passed = false;
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
1