I'm using a custom query to get product categories and I want the in-stock product count with them too, I managed to get the count but it shows out-of-stock count too which I don't want :(
Any idea how we can exclude the out-of-stock product count from the in stock?
I did some research and found out we can exclude out-of-stock products https://prnt.sc/8wpCstT_-jrf but it removes the products from the shop page too, I just want to remove them from the count, here is my code:
Thanks in Advance :)
function newcats_shortcode() {
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 1; // 1 for yes, 0 for no
$pad_counts = 1; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .' '. $cat->count .'</a>';
// echo "<pre>", var_dump($cat) ,"</pre>";
}
}
}
add_shortcode( 'newcats', 'newcats_shortcode' );
My Answer:
> One way to exclude out-of-stock products from the count is to modify your query to only include products that are in stock. You can do this by adding a meta query to your args array that filters out products with a stock status of "outofstock". Here's an example of how you can modify your code:
php
function newcats_shortcode() {
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 1; // 1 for yes, 0 for no
$pad_counts = 1; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty,
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '='
)
)
);
$categories = get_categories($args);
// Rest of your code to display categories
}
This code adds a meta query to your args array that filters out products with a stock status of "outofstock". This should exclude out-of-stock products from the count while still displaying them on the shop page.
Rate this post
3 of 5 based on 1532 votesComments