How to Query Posts by Custom Field in WordPress (meta_query)

Query posts by custom field with meta_query

Custom fields are often used for things you later want to filter by: the city of an event, its date, a “featured” flag. WP_Query can filter by them with the meta_query argument, from a simple equality check to ranges and several conditions combined with AND/OR.

Problem: You need a list of posts whose custom field has a certain value, is in a range, or simply exists.

Solution: Pass a meta_query array to WP_Query. Each clause has a key, a value, a compare operator and, for numbers and dates, a type.

One field

Posts of the event type where the field event_featured is 1:

<?php
$query = new WP_Query( array(
    'post_type'  => 'event',
    'meta_query' => array(
        array(
            'key'     => 'event_featured',
            'value'   => '1',
            'compare' => '=',
        ),
    ),
) );

Several conditions

Events in Kyiv from today on. Dates must be stored as Y-m-d (or Ymd), so that comparing them works:

<?php
$query = new WP_Query( array(
    'post_type'  => 'event',
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key'   => 'event_city',
            'value' => 'Kyiv',
        ),
        array(
            'key'     => 'event_date',
            'value'   => current_time( 'Y-m-d' ),
            'compare' => '>=',
            'type'    => 'DATE',
        ),
    ),
    'meta_key' => 'event_date',
    'orderby'  => 'meta_value',
    'order'    => 'ASC',
) );

current_time() uses the time zone from Settings → General, date() would use the server’s one. Without 'type' => 'NUMERIC' numbers are compared as strings, and “100” is less than “20”.

Field exists or not

Posts that have a featured image:

<?php
$query = new WP_Query( array(
    'post_type'  => 'post',
    'meta_query' => array(
        array(
            'key'     => '_thumbnail_id',
            'compare' => 'EXISTS',
        ),
    ),
) );

The compare operators: =, !=, >, >=, <, <=, LIKE, NOT LIKE, IN, NOT IN, BETWEEN, NOT BETWEEN, EXISTS, NOT EXISTS. For IN and BETWEEN the value is an array.

To change the main query of an archive in the same way, pass these arguments in pre_get_posts, as shown in changing the arguments of the global query.

NOTE: Every meta clause is a JOIN on the postmeta table, which has an index on meta_key but not on meta_value. On a large site several clauses become slow. If you mostly filter by a field (“featured”, “city”), a taxonomy is usually the faster and simpler choice.