Using get_posts with arguments found in meta keys

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.

Leave a Comment