Get all posts by post meta key and meta value

Advertisement

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.

Top ↑

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

Top ↑

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

Top ↑

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.

<?php
/**
* Get all post by post meta key and meta value.
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*/
if( ! function_exists( 'prefix_search_post_by_post_meta_value' ) ) :
function prefix_search_post_by_post_meta_value() {
$query_args = array(
'post_type' => 'post',
// Query performance optimization.
'fields' => 'ids',
'no_found_rows' => true,
'posts_per_page' => –1,
'meta_query' => array(
array(
'key' => 'my-meta-key',
'value' => 'my-meta-value',
),
)
);
$query = new WP_Query( $query_args );
if ( $query->posts ) {
foreach ( $query->posts as $key => $post_id ) {
// var_dump( $post_id );
// Code goes here..
}
}
}
add_action( 'admin_head', 'prefix_search_post_by_post_meta_value' );
endif;

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.

Leave a Reply

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

%d bloggers like this: