I need build a query like these :
Fetch 10 posts from any post_type but if the post_type was product then only add it if it is instock.
When i use meta_query for this purpose it only returns products ! because that meta is not available on other posts.
What can i do ?

  • Yes - if your instock data is a meta field, adding that condition as a meta query will only return items that have that value in that field.
    – jdm2112
    Nov 15 '16 at 18:52
  • You can use pre_get_posts to add the special query for the product. If you use the post_status : publish and set woocommerce options to hide if the product has no stock, it can work too.
    – Benoti
    Nov 15 '16 at 22:39

You can check status instock only if meta key _stock_status exists.

Something like:

'meta_query' => array(
                'key' => '_stock_status',
                'value' => 'instock',
                'compare' => '=',
            'relation' => 'OR',
                'key' => '_stock_status',
                'value' => '',
                'compare' => 'NOT EXISTS'

Note: Code is not tried or tested, so check for any syntax errors

  • Thank you so much, your snippet works fine and resolved my problem. I was really going to use what others mentioned but you saved my life.
    – f.n174
    Nov 16 '16 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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