Предотвращение заказов смешивания продуктов из некоторых категорий - PullRequest
0 голосов
/ 06 ноября 2019

Я пытаюсь запретить пользователю заказывать товары из некоторых категорий, если они уже заказали у одной.

Например, если у пользователя уже есть продукт из одной из этих категорий, который нельзя заказать у других в этом списке

  • Обычный
  • Большой
  • Дети
  • Фитнес
  • Строитель еды

Но они все еще могут заказать из категории Дополнительные предметы.

Я искалв этом случае ниже, однако в моем случае первый товар в корзине может быть из дополнительных предметов, и они разрешены, поэтому мне нужен цикл, но я просто не могу его решить.

Woocommerce - PreventДобавление товаров из двух разных категорий в корзину

Заранее спасибо

1 Ответ

0 голосов
/ 06 ноября 2019

Я нашел решение для моей петли

function get_product_top_level_category($prod_id) {

        $cat = get_the_terms( $prod_id, 'product_cat' );
        $return_array = array();

        foreach ($cat as $category) {
            if($category->parent == 0){
            $return_array[] = $category->term_id;
            }
        }
        return $return_array;
    }

    add_filter ( 'woocommerce_before_cart', 'restrict_cart_for_a_single_category' );
    function restrict_cart_for_a_single_category() {
        global $woocommerce;
        $cart_contents    =  $woocommerce->cart->get_cart( );
        $cart_item_keys   =  array_keys ( $cart_contents );
        $cart_item_count  =  count ( $cart_item_keys );

        // Do nothing if the cart is empty or has only one item
        if ( ! $cart_contents || $cart_item_count == 1 ) {
                return null;
        }

        // Multiple Items in cart
        $categories_not_allowed_mixing = array(
            'Fitness',
            'Kids',
            'Large',
            'Meal Builder',
            'Regular'
        );

        $categories_found = array();

        // Now we check each subsequent items top-level parent category
        foreach ( $cart_item_keys as $key ) {
            $product_id            =  $cart_contents[$key]['product_id'];
            $product_top_category  =  get_product_top_level_category( $product_id );

            foreach ($product_top_category as $top_category) {
                $product_top_category_term  =  get_term ( $top_category, 'product_cat' );
                $product_top_category_name  =  $product_top_category_term->name;

                if(in_array($product_top_category_name, $categories_not_allowed_mixing)) {
                    if(in_array($product_top_category_name, $categories_found)) {
                        // if category name is already in the array do nothing as multiples are allowed
                    } else {
                        $categories_found[] = $product_top_category_name;
                        // check how many of the category 
                    }
                }

                if ( count($categories_found) > 1 ) {
                        $woocommerce->cart->set_quantity ( $key, 0, true );
                        $restrict_categories  =  1;
                }
            }
        }

        // code to display the message or warning only once for any user
        if ( isset ( $restrict_categories ) ) {
                echo '<p class="woocommerce-error">You can not mix meal plans with other products, we have removed the additional items from your cart. </p>';
                //add your code for redirection here

        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...