Using get_posts with arguments found in meta keys

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

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

Is it possible to do this and if so how?

Marvellous

Related posts

Leave a Reply

2 comments

  1. 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.

  2. 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 );