我有一个商店,包含5个类别。这是多供应商,由于运输的复杂性,当他们独自在购物车时,我只能从一个特定类别('油漆')销售产品。因此,当购物车中含有油漆时,我需要防止添加任何非油漆产品,并显示错误消息,并且我需要防止将油漆产品添加到包含任何其他类别的购物车中,并消除错误消息。防止添加到购物车,如果购物车包含特定类别(WooCommerce)
我试着凑齐这些代码片段,我发现躺在Stackoverflow和其他地方。逻辑似乎在我的大脑中工作,但是当我尝试实现代码(通过functions.php)时,它会阻止任何产品被添加到购物车,除非购物车是空的。
这里是我的代码:
//*** Prevent mixture of paint and other prods in same cart ***//
function dont_add_paint_to_cart_containing_other() {
// Set flag false until we find a product in cat paint
$cat_check = false;
// Set $cat_check true if a cart item is in paint cat
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
if (has_term('paint', 'product_cat', $product->id)) {
$cat_check = true;
// break because we only need one "true" to matter here
break;
}
}
// Return true if cart empty
if (WC()->cart->get_cart_contents_count() == 0) {
return true;
}
// If cart contains paint and product to be added is not paint, display error message and return false.
elseif ($cat_check && get_queried_object()->term_id != '245778522') {
wc_add_notice('Sorry, you can only purchase paint products on their own. To purchase this product, please checkout your current cart or empty your cart and try again' , 'error');
return false;
}
// If cart contains a product that is not paint and product to be added is paint, display error message and return false.
elseif (!$cat_check && get_queried_object()->term_id = '245778522') {
wc_add_notice('Sorry, you can only purchase paint products on their own. To purchase this product, please checkout your current cart or empty your cart and try again' , 'error');
return false;
}
// Otherwise, return true.
return true;
}
add_filter('woocommerce_add_to_cart_validation', 'dont_add_paint_to_cart_containing_other');
谢谢你,ashvek。你是温柔的人和学者。 –
请标记答案的权利 – ashvek