У меня есть категория 'предзаказ', в которой я использовал код здесь , чтобы остановить добавление любых других категорий товаров, если предзаказ находится в корзине.
Я хочу такжезапретить использование нескольких разных продуктов из категории «Предзаказ», но разрешить использование нескольких одинаковых товаров.
В настоящее время в файле functions.php моей дочерней темы выполняется следующее:
add_action( 'woocommerce_check_cart_items', 'checking_cart_items' );
function checking_cart_items() {
global $woocommerce; // if needed, not sure (?)
$special = false;
$catx = 'preorder';
$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 'preorder' 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 'preorder' item in cart
{
if ( $number_of_items == 1 ) { // only one 'preorder' item in cart
if ( empty( $notice ) ){
$notice = '1';
}
}
if ( $number_of_items >= 2 ) { // 'preorder' 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 woocommerce notices
if ( $notice == '1' ) { // message for an 'preorder' item only (alone)
wc_add_notice( sprintf( '<p class="woocommerce-error">One pre-order item in cart</p>' ), 'success' );
} elseif ( $notice == '2' ) { // message for an 'preorder' item and other ones => removed other ones
wc_add_notice( sprintf( '<p class="woocommerce-error">Pre-order items must be purchased individually. Other items have 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' );
}
}
AmЯ могу использовать аналогичный цикл, чтобы проверить наличие нескольких «предзаказанных» товаров в корзине и удалить один?