Query Posts by ACF Field Values with WP_Query

Use meta_query in WP_Query to filter and sort posts by ACF field values.

php querying
|

Use meta_query in WP_Query to filter and sort posts by ACF field values.

Filter posts by a text field value:

<?php
$posts = new WP_Query( [
    'post_type'  => 'event',
    'meta_query' => [
        [
            'key'     => 'city',
            'value'   => 'Melbourne',
            'compare' => '=',
        ],
    ],
] );

Combine multiple conditions with AND/OR:

<?php
$posts = new WP_Query( [
    'post_type'  => 'property',
    'meta_query' => [
        'relation' => 'AND',
        [
            'key'     => 'price',
            'value'   => 500000,
            'compare' => '<=',
            'type'    => 'NUMERIC',
        ],
        [
            'key'     => 'bedrooms',
            'value'   => 3,
            'compare' => '>=',
            'type'    => 'NUMERIC',
        ],
    ],
] );

Sort by a numeric ACF field (use meta_value_num, not meta_value):

<?php
$posts = new WP_Query( [
    'post_type'  => 'product',
    'meta_key'   => 'price',
    'orderby'    => 'meta_value_num',
    'order'      => 'ASC',
] );

Filter by an ACF date picker field (dates are stored in Ymd format):

<?php
$today = date( 'Ymd' );

$posts = new WP_Query( [
    'post_type'  => 'event',
    'meta_query' => [
        [
            'key'     => 'event_date',
            'value'   => $today,
            'compare' => '>=',
            'type'    => 'DATE',
        ],
    ],
    'meta_key'   => 'event_date',
    'orderby'    => 'meta_value',
    'order'      => 'ASC',
] );

Filter by a true/false (boolean) field:

<?php
$posts = new WP_Query( [
    'post_type'  => 'post',
    'meta_query' => [
        [
            'key'     => 'is_featured',
            'value'   => '1',
            'compare' => '=',
        ],
    ],
] );

Related Snippets

Stay Updated

Get ACF tips and new extensions in your inbox

No spam. Unsubscribe anytime.