Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfsarmento/333c280f148cbcc456b1d4ed0b6c1392 to your computer and use it in GitHub Desktop.
Save nfsarmento/333c280f148cbcc456b1d4ed0b6c1392 to your computer and use it in GitHub Desktop.
Prevent mixture of a specific category and other products in same cart
/*
* Prevent mixture of a specific category and other products in same cart
*/
function ns_dont_add_booklet_to_cart_containing_other($validation, $product_id) {
// Set flag false until we find a product in cat booklet
$cart_has_booklets = false;
// Set $cat_check true if a cart item is in booklet cat
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
if (has_term('booklet', 'product_cat', $product->id)) {
$cart_has_booklets = true;
// break because we only need one "true" to matter here
break;
}
}
$product_is_booklets = false;
if (has_term('booklet', 'product_cat', $product_id)) {
$product_is_booklets = true;
}
// Return true if cart empty
if (!WC()->cart->get_cart_contents_count() == 0) {
// If cart contains booklet and product to be added is not booklet, display error message and return false.
if ($cart_has_booklets && !$product_is_booklets) {
wc_add_notice('Due to technical difficulties we are currently unable to process free, paid for or marketing products in the same order. Please note this is only temporary while we work hard to find a long term solution. We are sorry for any inconvenience this may cause. If you experience any difficulties please raise a ticket through our <a href="https://helpdesk.autismeducationtrust.org.uk/"> helpdesk</a>', 'error');
$validation = false;
}
// If cart contains a product that is not booklet and product to be added is booklet, display error message and return false.
elseif (!$cart_has_booklets && $product_is_booklets) {
wc_add_notice('Due to technical difficulties we are currently unable to process free, paid for or marketing products in the same order.Please note this is only temporary while we work hard to find a long term solution. We are sorry for any inconvenience this may cause. If you experience any difficulties please raise a ticket through our <a href="https://helpdesk.autismeducationtrust.org.uk/"> helpdesk</a>', 'error');
$validation = false;
}
}
// Otherwise, return true.
return $validation;
}
add_filter('woocommerce_add_to_cart_validation', 'ns_dont_add_booklet_to_cart_containing_other', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment