Created
January 9, 2020 13:09
-
-
Save nfsarmento/333c280f148cbcc456b1d4ed0b6c1392 to your computer and use it in GitHub Desktop.
Prevent mixture of a specific category and other products in same cart
This file contains 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
/* | |
* 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