Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce product query for stock status

I use 3 statuses of availability: 'in stock', 'out of stock' and 'allow for backorders'. I want export products which is only 'in stock' status to XML. The problem is that woocommerce returns value "instock" for both statuses: 'in stock' and 'allow for backorders'. Now the query looks like:

$query = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'meta_query' => array(
        array(
            'key' => '_stock_status',
            'value' => 'instock'
        )
    )
);
$wp_query = & new WP_Query($query);
while ($wp_query->have_posts()) : $wp_query->the_post();

And it export products with 'instock' and 'backorders_allowed' statuses. Maybe there is the way to exclude products with 'backorders_allowed'.

like image 312
Maria Puchkova Avatar asked Mar 24 '16 16:03

Maria Puchkova


1 Answers

It's highly recommended to use WC_Product_Query() instead of WP_Query().

So, i am showing how you can do this using WC_Product_Query().

$query_args = array(
    'limit'   => 10, //or whatever number of products you want to get.
    'stock_status' => 'instock' // or 'outofstock' or 'onbackorder' 
);

$query = new WC_Product_Query( $query_args );
$products = $query->get_products();

Note: If you want to include multiple stock_status, you can just simply use an array.

'stock_status' => array('instock', 'outofstock', 'onbackorder') 
like image 193
Mehbub Rashid Avatar answered Sep 30 '22 18:09

Mehbub Rashid