How to query only for products with status “in stock” in WooCommerce? [closed]

I am trying to build a query that only pulls back products that are in stock within a given product category.

Here is my working code where I pull all items back in the category and then I have to loop through them until I verify there is one that is in stock.

function CheckCategoryStock( $catToCheck ) {

    $args = array(
        'posts_per_page' => -1,
        'post_type'      => 'product',
        'hide_empty'     => 1,        
        'product_cat'    => $catToCheck,
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) : $query->the_post();
            global $product;
            if ( $product->is_in_stock() ) {
                $catCounter = 0;
                return 1;
            }        
        endwhile;
    }    

    return 0;

}    

Doing it this way works, but sometimes the code is slow because it has to loop through a number of products before it locates one that is in stock.

1
1

That worked great!

Just added this:

        'meta_query' => array(
        array(
            'key' => '_stock_status',
            'value' => 'instock',
            'compare' => '=',
        )
    )      

Thanks!

Leave a Comment