For some situations, we need to get all the posts which have specific meta key and meta value.
We can do it with the help of the WP_Query class.
Note: I’m giving you an imaginary example just for a reference to understand, In which situation you can use below code snippet.
- We have a custom post type
- We have 15 properties are published.
- We have store the location of each property in meta key
- And, We want to get all the properties which meta key is
property-locationwith meta value
$query_args = array( 'post_type' => 'properties', 'meta_query' => array( array( 'key' => 'property-location', 'value' => 'Pune', ), ) ); $query = new WP_Query( $query_args );
post_type is our custom post type slug. In our example its
key is meta key. In our example its
value is meta value. In our example its
You can use below complete gist code snippet for reference.
Note: In below code snippet you need to change the parameters as you need.
I have added some extra parameters to optimize the WordPress query.
idswhich return ONLY array post IDs of all found items.
truewhich optimizes the query.
-1to get all the posts. Default it return only 10 items.