2016-02-09 75 views
0

我正在查找限制用戶添加來自不同產品類別的產品的代碼。即,如果用戶從A類別添加產品,並且他試圖從B類別添加產品,則會出現一條消息,指出「您可以一次從一個類別下訂單並重定向到鏈接。」如何防止添加產品從woocommerce兩個類別?

回答

-1

這不是完美的答案按您的要求和需要做一些修改,但可以肯定會給你一個線索的解決方案:

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 
     $first_item     = $cart_item_keys[0]; 
     $first_item_id     = $cart_contents[$first_item]['product_id']; 
     $first_item_top_category  = get_product_top_level_category ($first_item_id); 
     $first_item_top_category_term = get_term ($first_item_top_category, 'product_cat'); 
     $first_item_top_category_name = $first_item_top_category_term->name; 

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

         if ($product_top_category != $first_item_top_category) { 
           $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 place order from one category at a time. </p>'; 
       //add your code for redirection here 
       wp_redirect($location, $status); 
           exit; 
     } 
} 
?> 

希望幫助

+0

看起來很從這裏被複制,而參考:https://開頭計算器。 com/questions/26373256/woocommerce-prevent-adding-items-from-two-different-categories-to-cart shame on you! – Silentdrummer

相關問題