1

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.

closed as off-topic by Mark Kaplun, Dave Romsey, cjbj, bosco, Howdy_McGee Apr 3 '17 at 15:30

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

6

That worked great!

Just added this:

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

Thanks!

  • 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.