2016-07-15 3 views
3

우리는 독점 카테고리 X 및 기타 정규 카테고리 Y을 보유하고 있습니다. 내가 좋아하는 것이 무엇 :WooCommerce 카트 - 조건부 상품 범주 유효성 검사

사람이 카테고리 X에서 아무것도를 주문하면, 다른 카테고리 항목이 장바구니에 추가 할 수 없습니다 및
  • 카테고리 Y 제품 X와 혼합하지 말아야 경고를 표시해야
    • .

    어떻게하면됩니까?

    나는 다른 포스트에서이 코드를 가지고 있지만 오래된 및 만족스럽지 :

    <?php 
    
    // Enforce single parent category items in cart at a time based on first item in cart 
    function get_product_top_level_category ($product_id) { 
    
        $product_terms   = get_the_terms ($product_id, 'product_cat'); 
        $product_category   = $product_terms[0]->parent; 
        $product_category_term = get_term ($product_category, 'product_cat'); 
        $product_category_parent = $product_category_term->parent; 
        $product_top_category  = $product_category_term->term_id; 
    
        while ($product_category_parent != 0) { 
          $product_category_term = get_term ($product_category_parent, 'product_cat'); 
          $product_category_parent = $product_category_term->parent; 
          $product_top_category  = $product_category_term->term_id; 
        } 
    
        return $product_top_category; 
    } 
    
    add_filter ('woocommerce_before_cart', 'restrict_cart_to_single_category'); 
    function restrict_cart_to_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 
        // Do nothing if the cart only has 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); 
              $mismatched_categories = 1; 
            } 
          } 
        } 
    
        // we really only want to display this message once for anyone, including those that have carts already prefilled 
        if (isset ($mismatched_categories)) { 
          echo '<p class="woocommerce-error">Only one category allowed in cart at a time.<br />You are currently allowed only <strong>'.$first_item_top_category_name.'</strong> items in your cart.<br />To order a different category empty your cart first.</p>'; 
        } 
    } 
    ?> 
    

    감사

    모든처럼
  • 답변

    3

    이 독점 카테고리 category X 주위를 선회하는, 당신을위한 조건을 사용할 필요가 이 카테고리.

    Woocommerce 제품 카테고리와 함께 사용할 수있는 특별한 기능이 있기 때문에 가능성이 있습니다. **cat_x**은 독점적 인 카테고리의 슬러그이며, 알고 계시 듯이 product_cat이 제품 카테고리를 가져 오는 인수입니다. has_term() 조건 기능 그래서

    , 당신은이를 사용하려고 :

    우리는 foreach 루프에서 카트 항목 2 번 실행해야
    if (has_term ('cat_x', 'product_cat', $item_id)) { // or $product_id 
        // doing something when product item has 'cat_x' 
    } else { 
        // doing something when product item has NOT 'cat_x' 
    } 
    

    :

    • 경우 감지하기가 그 차에있는 cat_x 상품입니다.
    • 카트의 한 항목에 대해 cat_x이 있으면 다른 항목을 제거하고 올바른 메시지를 발생시킵니다.

    아래 코드에서 좀 더 유용한 후크로 변경했습니다. 이 고리는 장바구니에있는 것을 확인합니다. 카트에 'cat_x'항목이 추가되면 카트의 다른 카테고리 항목을 제거하는 것이 좋습니다.

    코드는 잘 설명되어 있습니다. 결국 당신은 해고되는 다른 통지를 발견 할 것이다. 당신은 각각에 실제 텍스트를 넣어야합니다. 내가 정말이 코드를 테스트하는

    add_action('woocommerce_check_cart_items', 'checking_cart_items'); 
    function checking_cart_items() { 
    
        global $woocommerce; // if needed, not sure (?) 
        $special = false; 
        $catx = 'cat_x'; 
        $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 'cat_x' 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 'cat_x' item in cart 
          { 
           if ($number_of_items == 1) { // only one 'cat_x' item in cart 
            if (empty($notice)){ 
             $notice = '1'; 
            } 
           } 
           if ($number_of_items >= 2) { // 'cat_x' 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 'cat_x' item only (alone) 
          wc_add_notice(sprintf('<p class="woocommerce-error">bla bla bla one category X item in the cart</p>'), 'success'); 
         } elseif ($notice == '2') { // message for an 'cat_x' item and other ones => removed other ones 
          wc_add_notice(sprintf('<p class="woocommerce-error">bla bla bla ther is already category X in the cart => Other category items has 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'); 
         } 
        } 
    }  
    


    @edit

    우리는 통지 것보다 다른 것을 사용할 수 있습니다 ... (하지만 오류가 발생하지 않음) 할 수 없습니다 ... 모든 것이 가능하다. 그러나 좋은 조정 솔루션 인 좋은 조정 솔루션입니다.

    당신은 내가 아주 많이 감사 솔루션을 가지고 같은

    +0

    보이는 ... (처음에) 실제 카테고리 슬러그 에 의해 'cat_x'를 교체해야합니다. –

    +0

    @BluecupsSolution 그냥 환영합니다 :) ... 나는이 답변에 대해 완전히 확신하지 못했습니다. 추가 정보가 필요하면 여기에 의견을 남기십시오. 감사 – LoicTheAztec