2016-06-16 4 views
1

私はthis scriptが見つかりました:WooCommerce:私はWooCommerce内のショッピングカートのアイコンの上にカートのコンテンツの合計を表示することができ、製品の種類別カート回数

<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart'); ?>"><?php echo sprintf (_n('%d item', '%d items', WC()->cart->get_cart_contents_count()), WC()->cart->get_cart_contents_count()); ?> - <?php echo WC()->cart->get_cart_total(); ?></a> 

100個の項目が私のカートにある場合、それは100

示し

本当に必要なのは、アイテムの種類ごとにカウントを表示することです。だから、Tシャツ50枚とショート50枚があれば、2種類のアイテムタイプを個別に表示したいと思う。

これを達成する方法を知っている人はいますか?私は特定の製品カテゴリのカートの数を表示するには、この機能を構築してい

おかげ

答えて

1

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; 
       } 
      } 
     } 
    } 
    // Returning category count 
    if ($cat_count != 0) { 
     returm $cat_count; 
    } else { 
     returm ''; 
    } 
} 

あなたは、あなたのアクティブな子テーマのfunction.phpファイルに上記のコードを貼り付けますまたはテーマ。 cat_cart_count("shorts")WC()->cart->get_cart_contents_count()を交換します:あなたはそれをこのように使用するカテゴリ"shorts"については

カスタマイズでWooThemesは** "tshirts""short"カテゴリのためにそれを使用してコードスニペット:**

<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart'); ?>"><?php echo sprintf (_n('%d t-shirt', '%d t-shirts', cat_cart_count("tshirt")), cat_cart_count("tshirt")); ?> - <?php echo sprintf (_n('%d short', '%d shorts', cat_cart_count("shorts")), cat_cart_count("shorts")); ?> - <?php echo WC()->cart->get_cart_total(); ?></a> 

私は、製品名について完全にわからない(私はこのコードをテストしていないので)、代わりに製品スラッグになる可能性があります。だから、あなたは必ず両者でテストしなければなりません。

最後にカスタマイズしたスニペットコードで、テキストやその他のものを追加する方法をカスタマイズできます... "item(s)"をカテゴリ名で置き換えます。

+0

あなたの返信は私にとって完璧に機能しました。どうもありがとうございました! –

関連する問題