I had a task last week where I needed to display products having a specific minimum quantity in stock. I looked around but couldn’t find a solution. However, after some digging around I came across a solution in the form of meta_query.
The meta_query class handles meta-specific queries and generates the necessary SQL to do the query. So in order for me to filter products by stock quantity, I’d have to add meta query to the main WordPress loop that is responsible for outputting the products in the shop page. The meta associated with stock quantity is _stock.
Here’s the code that you can use. This implementation is by no means complete. Use the appropriate method to add the code to your pages making sure that you follow WordPress best practices.
global $wp_query; $meta_query = array('meta_query' => array( array( 'key' => '_stock', 'value' => '5', 'compare' => '>=', 'type' => 'NUMERIC' ) ) ); $args = array_merge( $wp_query->query_vars, $meta_query ); query_posts( $args );
A couple of things to note:
- compare key: this allows you to specify a way to compare the meta value. In my case I wanted to only show products with a quantity of 5, so I used ‘>=’,
- type key: this is important for the comparison to work well. Depending on the type you want to compare, use the appropriate compare tag
That’s all there is to it. If you have any comments/suggestions please share them in the comments section.