Restringindo itens do carrinho para pertencer à mesma categoria de produto
Estou usando o código abaixo para remover outros itens da categoria de produto WooCommerce do carrinho quando houver um item com uma categoria de produto especial 'cat_x' adicionada no carrinho e exibir alguns avisos personalizados diferentes. O código veio deesta discussão e simplesmente funciona bem:
add_action( 'woocommerce_check_cart_items', 'checking_cart_items' );
function checking_cart_items() {
$special = false;
$catx = 'cat_x';
$number_of_items = sizeof( WC()->cart->get_cart() );
if ( $number_of_items > 0 ) {
// Loop through all cart products
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$item = $values['data'];
$item_id = $item->id;
// detecting if 'cat_x' item is in cart
if ( has_term( $catx, 'product_cat', $item_id ) ) {
if (!$special)
$special = true;
}
}
// Re-loop through all cart products
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$item = $values['data'];
$item_id = $item->id;
if ( $special ) // there is a 'cat_x' item in cart
{
if ( $number_of_items == 1 ) { // only one 'cat_x' item in cart
if ( empty( $notice ) )
$notice = '1';
}
if ( $number_of_items >= 2 ) { // 'cat_x' item + other categories items in cart
// removing other categories items from cart
if ( !has_term( $catx, 'product_cat', $item_id ) ) {
WC()->cart->remove_cart_item( $cart_item_key ); // removing item from cart
if ( empty( $notice ) || $notice == '1' )
$notice = '2';
}
}
} else { // Only other categories items
if ( empty( $notice ) )
$notice = '3';
}
}
// Firing notices
if ( $notice == '1' ) { // message for an 'cat_x' item only (alone)
wc_add_notice( sprintf( '<p class="woocommerce-error">bla bla bla one category X item in the cart</p>' ), 'success' );
} elseif ( $notice == '2' ) { // message for an 'cat_x' item and other ones => removed other ones
wc_add_notice( sprintf( '<p class="woocommerce-error">bla bla bla ther is already category X in the cart => Other category items has been removed</p>' ), 'error' );
} elseif ( $notice == '3' ) { // message for other categories items (if needed)
wc_add_notice( sprintf( '<p class="woocommerce-error">bla bla bla NOT category X in the cart</p>' ), 'success' );
}
}
}
Tem a função condicionalhas_term () funciona também com matrizes de categorias, tentei, em vez de uma categoria, definir uma matriz de categorias nesse código.Mas não está funcionando.
No entanto, minhas necessidades mudaram: não quero permitir que o cliente selecione itens de carrinho de diferentes categorias. Portanto, o carrinho deve sempre ter itens da mesma categoria de produto.
Alguma ajuda por favor?
Obrigado.