防止订单混合某些类别的产品

我试图阻止用户从某些类别中订购商品,如果他们已经从某个类别中订购了商品。

例如,如果用户已经拥有其中一个类别的产品,而无法从该列表中的其他类别中订购

  • 常规
  • 孩子
  • 健身
  • 膳食制作器

但是他们仍然可以从“其他项目”类别中订购。

我一直在下面查看此内容,但就我而言,购物车中的第一个项目可能来自其他项目,并且允许这些项目,因此我需要循环,但无法解决。

Woocommerce - Prevent Adding items from two different categories to cart

预先感谢

xiangjibo 回答:防止订单混合某些类别的产品

我找到了解决问题的方法

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,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

        }
    }
本文链接:https://www.f2er.com/3155174.html

大家都在问