Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

Marvellous

share|improve this question
add comment

2 Answers

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

1. meta_key and meta_value

<?php
get_posts(array(
   // 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:

<?php
get_posts(array(
   // more args here
   'meta_query' = array(
      // meta query takes an array of arrays, watch out for this!
      array(
         '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
add comment

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
add comment

Your Answer

 
discard

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.