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;

    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.


That worked great!

Just added this:

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


  • I am glad that it worked for you. If you mark this post as a vaild answer to your question this would help the "unanswered questions" statistics. ;-D And besides that, people see that they might find a solution for their problem here.
    – flomei
    Apr 2 '17 at 21:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.