Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

wordpress - 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>    
question from:https://stackoverflow.com/questions/65877722/woocommerce-get-total-of-out-of-stock-products-by-taxonomy-term

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...