我有一個商店,包含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