Answer the question
In order to leave comments, you need to log in
How to specify an exception for a category in a php script?
Hello!
The code:
add_filter('woocommerce_add_to_cart_validation', 'check_and_limit_cart_items', 10, 3);
function check_and_limit_cart_items ($passed, $product_id, $quantity) {
$category = 'subscriptions';
// Если корзина пуста
if ( WC()->cart->is_empty() )
return $passed;
// Поиск товаров из категории подписок
foreach (WC()->cart->get_cart() as $cart_item) {
if ( has_term($category, 'product_cat', $cart_item['product_id']) ) {
// Показать сообщение
wc_add_notice(__('A subscription is already in cart (Other items are not allowed in cart).', 'woocommerce' ), 'error');
// Не добавляем новые товары
return false;
}
}
return $passed;
}
foreach (WC()->cart->get_cart() as $cart_item) {
if ( has_term($category, 'product_cat', $cart_item['product_id']) ) {
// Show message
wc_add_notice(__('A subscription is already in cart (Other items are not allowed in cart).', 'woocommerce' ), 'error');
// Don't add new products
return false;
}
Answer the question
In order to leave comments, you need to log in
Hello.
Firstly,
>> Help me, please, to figure it out, since the night I have been trying different options with the string:
Strings , not a string.
Secondly, "string" has nothing to do with it.
// Запрет на добавление в корзину товаров из категории подписок,
// если уже есть товар из категории подписок в корзине
add_filter('woocommerce_add_to_cart_validation', 'for_subscriptions_limit_cart_items', 10, 3);
function for_subscriptions_limit_cart_items ($passed, $product_id, $quantity) {
$subscription_category = 'subscriptions';
// Если корзина пуста
if ( WC()->cart->is_empty() ) {
return $passed;
}
$subscription_in_cart = false;
// Поиск товаров из категории подписок в корзине
foreach (WC()->cart->get_cart() as $cart_item) {
if ( has_term($subscription_category, 'product_cat', $cart_item['product_id']) ) {
$subscription_in_cart = true;
}
}
if ($subscription_in_cart) {
// проверяем, что новый товар тоже из категории подписок
if ( has_term($subscription_category, 'product_cat', $product_id) ) {
// добавляем товар в корзину
return $passed;
// если новый товар не из категории подписок
} else {
// Показать сообщение
wc_add_notice(__('A subscription is already in cart (Other items are not allowed in cart).', 'woocommerce' ), 'error');
// Не добавляем новые товары
return false;
}
}
return $passed;
}
Why has_term is used, it also looks for tags and tags in publications but not in the object in the basket. Inside the loop, you will most likely have to make another loop to parse the product object, can you see what you get in the loop itself? Add a print to the loop
print_r($cart_item['product_id']);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question