私はカート内の商品数を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;
}
}
}
}
これは美しく機能しました。本当にありがとう。 –