Search code examples
wordpresswoocommercecustom-taxonomy

WooCommerce: Get total of out of stock products by taxonomy term


I have a custom Taxonomy (Brands) of which i'm wanting to show the below data for each of the categories.

  1. Brand Name
  2. Total number of products for that brand
  3. total number of out of stock products for that brand

what I have so far works for 1. & 2. above but unsure how I cant pull the number of out of stock products for each brand.

Any help would be greatly appreciated.

<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>    

Solution

  • Like that should be work:

    <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>