我的问题和代码直接基于这个问题 - ” 我有一个包含 5 个类别的商店。它是多供应商,由于运输的复杂性,当购物车中只有一个特定类别(“油漆”)的产品时,我只能销售它们。因此,当购物车包含油漆时,我需要防止将任何非油漆产品添加到购物车,并显示错误消息,我需要防止将油漆产品添加到包含任何其他类别的购物车,并显示错误消息。< /p>
我试图从我在 Stackoverflow 和其他地方发现的片段中拼凑出这段代码。该逻辑似乎在我的大脑中起作用,但是当我尝试实现代码(通过 functions.php)时,它会阻止任何产品添加到购物车,除非购物车是空的。”
问题链接 - Prevent add to cart if cart contains a specific category (WooCommerce)
我已经检查并修改了已接受的答案以满足我的需要,但是它似乎根本不起作用,因为我有相同的问题,只是与不同的类别(即气体而不是油漆)有关,据我所知,我会只需修改“has_term”函数即可使其正常工作,因为它只是指向特定类别的问题?
//*** Prevent mixture of gas and other prods in same cart ***//
function dont_add_gas_to_cart_containing_other($validation, $product_id) {
// Set flag false until we find a product in gas
$cart_has_gas = false;
// Set $cat_check true if a cart item is in gas cat
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
if (has_term('Gas', 'Gas Tanks & Accessories', $product->id)) {
$cart_has_gas = true;
// break because we only need one "true" to matter here
break;
}
}
$product_is_gas = false;
if (has_term('Gas', 'Gas Tanks & Accessories', $product_id)) {
$product_is_gas = true;
}
// Return true if cart empty
if (!WC()->cart->get_cart_contents_count() == 0) {
// If cart contains gas and product to be added is not gas, display error message and return false.
if ($cart_has_gas && !$product_is_gas) {
wc_add_notice('Sorry, you can only purchase Helium Gas products on their own. To purchase this product, please checkout your current cart or empty your cart and try again', 'error');
$validation = false;
}
// If cart contains a product that is not gas and product to be added is gas, display error message and return false.
elseif (!$cart_has_gas && $product_is_gas) {
wc_add_notice('Sorry, you can only purchase Helium Gas products on their own. To purchase this product, please checkout your current cart or empty your cart and try again', 'error');
$validation = false;
}
}
// Otherwise, return true.
return $validation;
}
add_filter('woocommerce_add_to_cart_validation', 'dont_add_gas_to_cart_containing_other', 10, 2);