Show only WooCommerce in stock products with a WP_Query Show only WooCommerce in stock products with a WP_Query wordpress wordpress

Show only WooCommerce in stock products with a WP_Query


Since WooCommerce 3, there is 2 ways to exclude "Out of stock" products on your WP_Query:

1) Including a Tax query like:

$products = new WP_Query( array(    'post_type' => 'product',    'meta_key' => 'total_sales',    'posts_per_page' => 6,    'orderby' =>'meta_value_num',    'order' => 'DESC',    'tax_query' => array( array(        'taxonomy' => 'product_visibility',        'field'    => 'name',        'terms'    => array('outofstock'),        'operator' => 'NOT IN'    ) ),) );

2) Including a Meta query like:

$products = new WP_Query( array(    'post_type' => 'product',    'meta_key' => 'total_sales',    'posts_per_page' => 6,    'orderby' =>'meta_value_num',    'order' => 'DESC',    'meta_query' => array( array(        'key'     => '_stock_status',        'value'   => 'outofstock',        'compare' => '!=',    ) ),) );

Both ways work.


You can add the in stock meta value param:

$best_sellers_args = array('post_type' => 'product', 'meta_key' => 'total_sales',        'posts_per_page' => 6,'orderby' =>'meta_value_num','order' => 'DESC','meta_query' => array(        array(            'key' => '_stock_status',            'value' => 'instock'        )    ));

See this blog post for further details: https://www.gavick.com/blog/wp_query-woocommerce-products

Good luck!