10
votes

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

2

2 Answers

16
votes

You can have multiple meta_query filters. See (http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters). By default the relationship between these filters is AND which is ok. You can add a filter for _back_order = no.

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

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')