Get all posts by post meta key and meta value

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.

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 value Pune.

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

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 value ids which return ONLY array post IDs of all found items.
  • no_found_rows with value true which optimizes the query.
  • posts_per_page with value -1 to get all the posts. Default it return only 10 items.

Author: Mahesh Waghmare

I'm a professional WordPress theme/plugin developer since 2012 from Pune, India.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.