2016-12-07 11 views
3

私はカート内の商品数をWooCommerceの特定の商品カテゴリから取得しようとしています。特定の商品カテゴリのカートアイテム数をカウントする

ワイナリー用のサイトを作成しています。それはアルコール性および非アルコール性の製品を有する。すべてのワインは、メインカテゴリ 'ワイン'またはカテゴリID 34の下にあり、その下には多くのサブカテゴリと製品があります。

このカテゴリに該当するものについては...このカテゴリのカートにはいくつのアイテムがあるのか​​知る必要があります。 6本のワインがある場合は、すべて同じ製品IDか6種類の製品IDであるかに関係なく私は「ワイン」やカテゴリID 34の6から6の番号を取得する必要があります。

私はこれを成功させずに試しました。

私はWooCommerceには非常に新しく、オブジェクト指向には少し新しくなっています。

おかげ

function cat_cart_count($cat_name) { 

// $cat_name variable is for you normally "tshirts" or "shorts" 

global $woocommerce; $cat_count = 0; 

// For each product in the cart 
foreach(WC()->cart->get_cart() as $cart_item_key => $values) { 
    $_product_id = $values['product_id']; // product ID 
    $_product_qty = $values['quantity']; // product quantity 

    // Getting categories of the product (could be more than one) 
    $terms = get_the_terms($_product_id, 'product_cat'); 

    // Checking this product has a category 
    if ($terms && ! is_wp_error($terms)) { 
     $term_name = array(); 

     // For each category of that product 
     foreach($terms as $term) { 

      // Adding the category name to an array 
      $term_name[] = $term->name; 

      // if the product has $cat_name category 
      if (in_array($cat_name, $term_name)) { 

       // add 1 x product quantity to the count 
       $cat_count =+ 1 * $_product_qty; 
      } 
     } 
    } 
} 

答えて

6

を作っこの を試してみたカテゴリID、スラグ、名前や配列を受け入れますその値の

これは、これを行うための簡単で簡単な方法です。あなたのコードははるかにコンパクトで軽量になります。また、カテゴリID を直接使用することもできます。ここで

はあなたの関数である:

function cat_cart_count($cat_name) { 
    $cat_count = 0; 

    // Iterating through each cart item 
    foreach(WC()->cart->get_cart() as $cart_item) 
     if(has_term($cat_name, 'product_cat', $cart_item['product_id'])) 
      $cat_count += $cart_item['quantity']; 

    return $cat_count; 
} 

このコードはテストされ、完全に機能しています。 34カテゴリIDの値を表示する例echoのために使用して、機能の

使用法:対応するための

echo cat_cart_count(34); 
+0

これは美しく機能しました。本当にありがとう。 –

0

は、私はWordpressの条件関数has_term()をインターネットからこのコードをコピーして、あなたのケースに合わせてアップデート

function check_product_in_cart() { 
     global $woocommerce; 
      // id of targeted category is 5 for example 

     $product_count = 0; 

     // start of the loop that fetches the cart items 

     foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) { 
      $_product = $values['data']; 
      $terms = get_the_terms($_product->id, 'product_cat'); 

      // second level loop search, in case some items have several categories 
      foreach ($terms as $term) { 
       $_categoryid = $term->term_id; 
       if (($_categoryid === 5) { 

        $product_count=+ 1 * $_product_qty; ; 
       } 
      } 
     } 

     return $product_count; 
    } 
+0

感謝。カテゴリidはこのcheck_product_in_cart()のかっこ内に入る必要がありますか? –

+0

を動的にしたい場合は、このcheck_product_in_cart($ cat_id)のようなメソッドを宣言し、そのメソッドの中の5を$ cat_idに置き換えます。 を使用し、メソッドを使用する必要があるcheck_product_in_cart(5)を記述します。 –

関連する問題