In this article we are going to see:
Description Description
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.
Advertisement
[ad1]
Example Example
Note: I’m giving you an imaginary example just for a reference to understand, In which situation you can use below code snippet.
Suppose,
- We have a custom post type
properties
. - We have 15 properties are published.
- We have store the location of each property in meta key
property-location
- And, We want to get all the properties which meta key is
property-location
with meta valuePune
.
Advertisement
[ad2]
Code Snippet Code Snippet
$query_args = array( 'post_type' => 'properties', 'meta_query' => array( array( 'key' => 'property-location', 'value' => 'Pune', ), ) ); $query = new WP_Query( $query_args );
Here,
– post_type
is our custom post type slug. In our example its properties
.
– key
is meta key. In our example its property-location
– value
is meta value. In our example its Pune
Advertisement
[ad3]
Gist Snippet Gist Snippet
You can use below complete gist code snippet for reference.
Note: In below code snippet you need to change the parameters as you need.
Here,
I have added some extra parameters to optimize the WordPress query.
fields
with valueids
which return ONLY array post IDs of all found items.no_found_rows
with valuetrue
which optimizes the query.posts_per_page
with value-1
to get all the posts. Default it return only 10 items.