0
我試圖阻止用戶將一個以上的商品從特定類別添加到購物車中。我發現這個功能:WooCommerce:購物車中的每個類別的一個產品
function cart_has_licence_in_it()
{
//Check to see if user has product in cart
global $woocommerce;
//assigns a default negative value
$product_in_cart = false;
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
$terms = get_the_terms($_product->id, 'product_cat');
if ($terms) {
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if ($_categoryid === 23) {
$product_in_cart = true;
}
}
}
}
return $product_in_cart;
}
我剛剛爲此更改了類別ID號。 現在我要檢查,如果車已經從該類別的項目,如果是這樣,從購物車中刪除的項目,並顯示一條消息:
add_filter('woocommerce_add_cart_item_data', 'woo_custom_add_to_cart');
function woo_custom_add_to_cart($cart_item_data) {
global $woocommerce;
$categorie = get_the_terms($cart_item_data->id, 'product_cat');
$_lacat = $categorie->term_id;
if (($_lacat===23)&&(cart_has_licence_in_it())) {
wc_add_notice('You cannot add this license to your cart because there is already another license in it. Please remove the other license from your cart first.', 'error');
$woocommerce->cart->remove_cart_item($cart_item_data->id);
}
else return $cart_item_data;
}
但它不工作,我不甚至得到消息。
由於我是一般的新手,對WordPress和PHP進行編碼,所以我很確定我的代碼中有很多錯誤。
如果你想第一個行爲(警告用戶,讓他們刪除項目themelves),你只需要改變過去'if'語句行: '//註釋或刪除此行:$ woocommerce - > cart-> remove_cart_item($ cart_item_key); $ message = sprintf('您不能從該類別訂購兩件商品;請先從您的購物車中刪除%s。',$ _ product-> get_title()); ' –