WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am using get posts, but I need to refine the query based on posts where a certain meta_key has a certain value.

Something like this

<?php $reviews = get_posts('post_type=reviews&numberposts=-1&   // eg. // location=berkshire');

Is it possible to do this and if so how?


share|improve this question

get_posts accepts any of the arguments that WP_Query accepts. So there's a few options.

1. meta_key and meta_value

   // some more args here
   'meta_key'   => 'some_key',
   'meta_value' => 'some value'

2. meta_query

meta_query is more sophisticated that using meta_key and meta_value. For instance, say you wanted to get posts that have the meta_key with one of three values:

   // more args here        
   'meta_query' => array(
      // meta query takes an array of arrays, watch out for this!
         'key'     => 'some_key',
         'value'   => array('anOption', 'anotherOption', 'thirdOption'),
         'compare' => 'IN'

There's a ton of examples for you to checkout in the custom fields section of WP_Query's documentation.

share|improve this answer

Yes. Its possible. Use meta_key and meta_value parameters. meta_key is for custom field key (e.g. location) and meta_value is for custom field value (e.g. berkshire).

Use the refined code below:

/* Query args. */
$args = array(
    'post_type' => 'reviews',
    'posts_per_page' => -1,
    'meta_key' => 'location', 
    'meta_value' => 'berkshire'

/* Get Reviews */
$reviews = get_posts( $args );
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.