How To Query Posts With Meta Keys & Values In WordPress

Looking to query posts with meta keys and values in WordPress? All you may need is to pass the meta_key and meta_value values through your argument’s array.

Using meta keys and values in WordPress

To query posts with a meta key and value, you must pass these arguments into your array. Use the below example as a reference.

$args = array(
 post_type => 'post',
 meta_key => 'example_meta_name',
 meta_value => 'example_meta_value',
 meta_compare => '='
);

Query with multiple meta keys

If you’re querying posts for multiple meta keys, use the code below to pass the meta_query argument.

$args = array(
 post_type => 'post',
 'meta_query' => array(
  'relation' => 'AND',
  array(
   'key' => 'example_meta_name_1',
   'value' => 'example_meta_value_1',
   'compare' => '='
  ),
  array(
   'key' => 'example_meta_name_2',
   'value' => 'example_meta_value_2',
   'compare' => '='
  )
 )
);

Meta compare argument

The meta_compare argument acts similar to the SQL operators, you can pass the following values into this argument:

=, !=, >, >=, <, <=, LIKE, NOT LIKE, IN, NOT IN, BETWEEN, NOT BETWEEN, EXISTS, NOT EXISTS, REGEXP, NOT REGEXP and RLIKE.