Created
September 11, 2022 18:34
-
-
Save CupCodeIr/7b08a566ab8e1bcfaec90d87b6bdc43f to your computer and use it in GitHub Desktop.
Limit WooCommerce Cart to include only one of the specific products and nothing else
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Return if product can be added to the cart | |
* @param $valid | |
* @param $product_id | |
* @return bool | |
*/ | |
function avoid_special_products_mix($valid, $product_id): bool | |
{ | |
$current_cart_items_count = WC()->cart->get_cart_contents_count(); | |
if ($current_cart_items_count > 0) { | |
// TODO Put specific product ids | |
$unmixable_products_id = []; | |
$unmixable_products_cart_ids = []; | |
foreach ($unmixable_products_id as $item) { | |
$unmixable_products_cart_ids[] = WC()->cart->generate_cart_id($item); | |
} | |
foreach ($unmixable_products_cart_ids as $item) { | |
if (WC()->cart->find_product_in_cart($item)) { | |
$valid = false; | |
break; | |
} | |
} | |
if (in_array($product_id, $unmixable_products_id)) { | |
$valid = false; | |
} | |
if (!$valid) | |
// Show an error in case of adding specific products with others in cart | |
wc_add_notice(sprintf(__("Empty <a href=\"%s\">your cart</a> first as selected product must be ordered separately.", "text-domain"), wc_get_cart_url()), 'error'); | |
} | |
return $valid; | |
} | |
add_filter('woocommerce_add_to_cart_validation', 'avoid_special_products_mix', 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment