WooCommerce:按分类术语获取缺货产品总数

时间:2021-01-25 01:06:38

标签: wordpress woocommerce custom-taxonomy

我有一个自定义分类法(品牌),我想显示每个类别的以下数据。

  1. 品牌名称
  2. 该品牌的产品总数
  3. 该品牌的缺货商品总数

到目前为止,我所拥有的产品适用于上述 1. 和 2.,但不确定如何为每个品牌提取缺货产品的数量。

任何帮助将不胜感激。

<table style="margin:0px;">
<?php  
    $terms = get_terms(array(
       'taxonomy' => 'Brand',
       'hide_empty' => false,
    ));

    foreach ($terms as $terms)
    {
        echo "<tr style='list-style:none;'>";
        echo "<td style='width: 200px'>".$terms->name."</td>";
        echo "<td style='width: 200px'>".$terms->count."</td>";
        echo "<td style='width: 200px'>Number of out of stock products for this category?</td>";
        echo "</tr>";
   }
?>
</table>    

1 个答案:

答案 0 :(得分:0)

应该是这样的:

<table style="margin:0px;">
<?php
    $taxonomy_name = "Brand";
    $terms = get_terms(array(
       'taxonomy' => $taxonomy_name,
       'hide_empty' => false,
    ));

    foreach ($terms as $term)
    {
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'meta_query' => array(
                array(
                    'key' => '_stock_status',
                    'value' => 'outofstock',
                )
            ),
            'tax_query' => array(
                array(
                'taxonomy' => $taxonomy_name,
                'field' => 'term_id',
                'terms' => $term->term_id
                )
            )
        );

        $query = new WP_Query($args);

        echo "<tr style='list-style:none;'>";
        echo "<td style='width: 200px'>$term->name</td>";
        echo "<td style='width: 200px'>$term->count</td>";
        echo "<td style='width: 200px'>$query->found_posts</td>";
        echo "</tr>";
   }
?>
</table>
相关问题