• Никакой политики на форуме. Иначе - бан!
  • Вопрос без рабочей ссылки на проблему считается риторическим. Без ссылки и скриншота - провокацией!
  • Темы озаглавленные с маленькой буквы или капсом удаляются без предупреждения!

Товары в корзине из одной категории

kadulin

Новичок
Всем привет, подскажите, как реализовать чтобы можно было купить товары только из одной категории? К примеру, есть несколько товаров в корзине из категории X, но один товар из категории Y, не дать покупателю перейти к оформлению и попросить его удалить товары из этой категории.
 

kimad

Опытный
Местный
Попробуйте следующий сниппет.

Код:
add_action( 'woocommerce_check_cart_items', 'prevent_checkout_product_category_based' );
function prevent_checkout_product_category_based() {

    // HERE set the product category slug
    $category = 'ucenennye-tovary';

    $found = $other = false; // Initializing variables

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // checking for the specific product category
        $term_slugs = wp_get_post_terms( $cart_item['product_id'], 'product_cat', array('fields' => 'slugs') );
        if( in_array($category, $term_slugs) ) {
            $found = true; // Targeted product category found
        }
        elseif( ! in_array($category, $term_slugs) && sizeof($term_slugs) > 0 ){
            $other = true; // Other product categories found
        }
    }
    // If the targeted product category is mixed with other product categories
    if ( $found && $other ) {
        // Display an error notice and avoid checkout
        wc_add_notice( __( "Товары категории Х оформляются отдельным заказом!" ), 'error' );
    }
}
 

Galatonoff

Новичок
Попробуйте следующий сниппет.

Код:
add_action( 'woocommerce_check_cart_items', 'prevent_checkout_product_category_based' );
function prevent_checkout_product_category_based() {

    // HERE set the product category slug
    $category = 'ucenennye-tovary';

    $found = $other = false; // Initializing variables

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // checking for the specific product category
        $term_slugs = wp_get_post_terms( $cart_item['product_id'], 'product_cat', array('fields' => 'slugs') );
        if( in_array($category, $term_slugs) ) {
            $found = true; // Targeted product category found
        }
        elseif( ! in_array($category, $term_slugs) && sizeof($term_slugs) > 0 ){
            $other = true; // Other product categories found
        }
    }
    // If the targeted product category is mixed with other product categories
    if ( $found && $other ) {
        // Display an error notice and avoid checkout
        wc_add_notice( __( "Товары категории Х оформляются отдельным заказом!" ), 'error' );
    }
}

Как бы да, но я так понял что чуток нужно по другому
Допустим есть категории
Тарелки / Кастрюли / чашки

Клиент добавляет рандомно товар из категорий
но оформить заказ он может только когда товары в корзине соответствуют только одной из всех категорий

в Вашем примере вы указали только определенную категорию
ucenennye-tovary
 

kadulin

Новичок
Как бы да, но я так понял что чуток нужно по другому
Допустим есть категории
Тарелки / Кастрюли / чашки

Клиент добавляет рандомно товар из категорий
но оформить заказ он может только когда товары в корзине соответствуют только одной из всех категорий

в Вашем примере вы указали только определенную категорию
ucenennye-tovary
Верно, чтобы в одном заказе были либо только "Тарелки" либо только "Кастрюли" и т.д.
 

kadulin

Новичок
Попробуйте следующий сниппет.

Код:
add_action( 'woocommerce_check_cart_items', 'prevent_checkout_product_category_based' );
function prevent_checkout_product_category_based() {

    // HERE set the product category slug
    $category = 'ucenennye-tovary';

    $found = $other = false; // Initializing variables

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // checking for the specific product category
        $term_slugs = wp_get_post_terms( $cart_item['product_id'], 'product_cat', array('fields' => 'slugs') );
        if( in_array($category, $term_slugs) ) {
            $found = true; // Targeted product category found
        }
        elseif( ! in_array($category, $term_slugs) && sizeof($term_slugs) > 0 ){
            $other = true; // Other product categories found
        }
    }
    // If the targeted product category is mixed with other product categories
    if ( $found && $other ) {
        // Display an error notice and avoid checkout
        wc_add_notice( __( "Товары категории Х оформляются отдельным заказом!" ), 'error' );
    }
}
Спасибо большое за ответ, выше верно подметили, можно как то решить этот вопрос?
 
Сверху Снизу