Get in-stock product count in a category

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' );