The meta_query argument in WP_Query filters posts by their custom field (post meta) values. You pass an array of clauses, each with a key, a value, a compare operator and an optional type, and join them with relation AND or OR. It works the same for fields you add yourself and fields created with Advanced Custom Fields.
The minimal working example looks like this:
$args = array(
'meta_query' => array(
array(
'key' => 'featured_post',
'value' => '1',
'compare' => '=',
),
),
);
$q = new WP_Query( $args );
To read a meta value off a single known post, use get_post_meta(). meta_query solves the inverse problem: finding the posts that match a meta condition. The examples below were checked against the WP_Meta_Query source and run on WordPress 7.1.4 in WordPress Playground, including the gotchas that return the wrong posts without any error. You’ll want to be comfortable adding code snippets to WordPress first.
meta_queryis aWP_Queryargument that filters posts by custom field (post meta) values, including fields created with ACF.- Each clause takes a
key, avalue, acompareoperator and atype. Clauses combine withrelationAND or OR and can be nested. - Values compare as text unless you set
type.NUMERICcasts to a whole number, so useDECIMAL(10,2)for prices. !=,NOT INandorderby => meta_valueall skip posts that don’t have the key at all. Add aNOT EXISTSclause with OR to keep them.
meta_query structure at a glance
'meta_query' => array(
'relation' => 'AND', // AND or OR (optional, default AND)
array(
'key' => 'field_name', // the custom field name
'value' => 'field_value', // not needed for EXISTS / NOT EXISTS
'compare' => '=', // optional, default '=' (or 'IN' for an array value)
'type' => 'CHAR', // optional, default 'CHAR'
),
// additional clauses or nested groups...
)
Each clause accepts four main parameters: key (the custom field name), value (what to match), compare (the operator) and type (how MySQL casts the stored value before comparing). A few rules from the core source are worth knowing:
- WordPress treats an array as a single clause (a “first-order clause”) only if it has a
keyor avalue. Any other array is read as a nested group of clauses. relationonly understands AND and OR. Anything else, including a typo, falls back to AND.- An unknown
comparevalue silently becomes=, and an unknowntypebecomesCHAR. Neither throws an error, so a typo just returns different posts. - Since WordPress 5.1 a clause also accepts
compare_key(for example LIKE on the key name), and since 5.3type_key.
Meta query comparison operators
WP_Meta_Query accepts 17 operators for compare. The table groups the four greater/less-than operators, and REGEXP with its synonym RLIKE. Operators are case-insensitive, so 'like' works too.
| Operator | What it matches | Value |
|---|---|---|
= | Equal to. Default when value is a single value | String |
!= | Not equal to. Skips posts without the key | String |
> >= < <= | Greater / less than. Set type for numbers and dates | String or number |
LIKE | Contains the substring (WordPress adds the % wildcards) | String |
NOT LIKE | Does not contain the substring | String |
IN | Matches any value in the list. Default when value is an array | Array |
NOT IN | Matches none of the values. Skips posts without the key | Array |
BETWEEN | Inside the range, inclusive | Array of 2 |
NOT BETWEEN | Outside the range | Array of 2 |
EXISTS | The post has the key. With a value, it behaves like = | None |
NOT EXISTS | The post has no row for the key. value is ignored | None |
REGEXP / RLIKE | Matches a MySQL regular expression (RLIKE is a synonym) | String (regex) |
NOT REGEXP | Does not match the regular expression | String (regex) |
When you use the meta_key/meta_value shorthand instead of the meta_query array, set the operator with meta_compare.
Simple meta_key and meta_value query
For a single custom field you don’t need the full meta_query array. WP_Query accepts meta_key, meta_value, meta_compare and meta_type as top-level parameters:
$args = array(
'post_type' => 'post',
'meta_key' => 'featured',
'meta_value' => 'yes',
'meta_compare' => '=',
);
$query = new WP_Query( $args );
This shorthand is fine for one condition. For multiple fields or nested logic, use the meta_query array shown in the sections below.
Query posts by a meta value
The most common use case is filtering posts by a single custom field value. Say your posts have a featured_post field that controls which posts appear in a featured section on your homepage:
$args = array(
'meta_query' => array(
array(
'key' => 'featured_post',
'value' => '1',
'compare' => '=',
),
),
'no_found_rows' => true,
'fields' => 'ids',
);
$q = new WP_Query( $args );
The no_found_rows and fields arguments are optional speedups. 'no_found_rows' => true skips the pagination count, and 'fields' => 'ids' returns post IDs instead of full post objects. Drop both if you need pagination or want to loop through post content with a standard WordPress loop.
meta_query combines with every other WP_Query argument using AND. Add 's' => 'keyword' and you get posts matching the search terms and the meta condition. The search itself still only looks at the title, excerpt and content, never at custom fields. The same arguments work for custom post types: set post_type and add the meta_query.
Query posts by multiple meta values
To check one meta key against several values, use IN and pass an array as the value:
$args = array(
'meta_query' => array(
array(
'key' => 'city_name',
'value' => array( 'New York City', 'London', 'San Francisco' ),
'compare' => 'IN',
),
),
);
$q = new WP_Query( $args );
This returns posts where city_name matches any of the three values. NOT IN returns the opposite. If you leave out compare and pass an array, WordPress switches to IN on its own.
Watch out for empty arrays. WP_Meta_Query removes an empty value array before building the SQL, which turns the clause into “has this key”. In testing, 'value' => array(), 'compare' => 'IN' returned every post with a color field instead of none. If the list comes from user input or another query, check it first:
if ( empty( $cities ) ) {
$posts = array(); // nothing to match, skip the query
} else {
$q = new WP_Query( array(
'meta_query' => array(
array( 'key' => 'city_name', 'value' => $cities, 'compare' => 'IN' ),
),
) );
}
Query posts by multiple meta keys
To filter by several custom fields at once, add one array per field inside meta_query and set relation:
$args = array(
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'city_name',
'value' => array( 'New York City', 'London', 'San Francisco' ),
'compare' => 'IN',
),
array(
'key' => 'featured_post',
'value' => '1',
'compare' => '=',
),
),
);
$q = new WP_Query( $args );
Use AND when every condition must match and OR when any one is enough. Each clause adds another join on the postmeta table, which matters on big sites (more on that in the performance section).
If you only want posts that have any one of several keys, key also accepts an array. 'key' => array( 'phone', 'email' ) matches posts with either field.
Nested meta queries
You can nest meta_query arrays for logic like “color is red AND (size is large OR size is medium)”:
$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => 'red',
),
array(
'relation' => 'OR',
array(
'key' => 'size',
'value' => 'large',
),
array(
'key' => 'size',
'value' => 'medium',
),
),
),
);
$query = new WP_Query( $args );
The outer relation is AND, so both conditions must be true. The inner group uses OR, so either size matches. Each group gets its own relation, and there’s no fixed depth limit. In practice two levels covers nearly everything, and each extra clause is another join.
Query posts between dates
For dates stored as YYYY-MM-DD strings, use BETWEEN with 'type' => 'DATE':
$args = array(
'meta_query' => array(
array(
'key' => 'my_date_field',
'value' => array( '2026-01-01', '2026-12-31' ),
'type' => 'DATE',
'compare' => 'BETWEEN',
),
),
);
$q = new WP_Query( $args );
ACF is different. Its Date Picker field always saves the value as Ymd (for example 20261231), whatever return format you pick. The return format only changes what get_field() gives back. So compare against Ymd values:
$args = array(
'post_type' => 'event',
'meta_query' => array(
array(
'key' => 'event_date', // ACF date picker field name
'value' => date( 'Ymd' ), // today, in the stored format
'compare' => '>=',
'type' => 'NUMERIC',
),
),
'meta_key' => 'event_date',
'orderby' => 'meta_value_num',
'order' => 'ASC',
);
ACF’s Date Time Picker stores Y-m-d H:i:s instead, so use 'type' => 'DATETIME' with that format.
If your dates are Unix timestamps, compare numbers:
$args = array(
'meta_query' => array(
array(
'key' => 'my_date_field',
'value' => array( strtotime( '2026-01-01' ), strtotime( '2026-12-31 23:59:59' ) ),
'type' => 'NUMERIC',
'compare' => 'BETWEEN',
),
),
);
$q = new WP_Query( $args );
Swap BETWEEN for >= or < with a single value to find posts after or before one date.
The type parameter
By default WordPress compares meta values as text, because meta_value is a text column. As text, “9” is greater than “50” because the first character wins. type tells MySQL to CAST the stored value before comparing:
| type | MySQL cast | Use it for |
|---|---|---|
CHAR (default) | No cast, plain text comparison | Text, exact matches, LIKE |
NUMERIC | SIGNED (whole number) | Integers like counts, IDs, years |
SIGNED / UNSIGNED | Whole number, with or without negatives | Integers |
DECIMAL(10,2) | Fixed-point number with 2 decimal places | Prices, ratings like 4.5 |
DATE | Date | YYYY-MM-DD values |
DATETIME | Date and time | YYYY-MM-DD HH:MM:SS values |
TIME | Time of day | HH:MM:SS values |
BINARY | Binary string | Case-sensitive matches |
One detail from the core source: NUMERIC is converted to SIGNED in the core source, which is a whole number. Decimals get cut off. Here is what four queries returned against products priced 9, 9.5, 10, 10 and 100:
| Query | Returned prices | Why |
|---|---|---|
price > 50, no type | 9, 9.5 | Text comparison: “9” sorts after “5” |
price > 50, NUMERIC | 100 | Correct |
price > 9, NUMERIC | 10, 10, 100 | 9.5 is cast to 9 and dropped |
price > 9, DECIMAL(10,2) | 9.5, 10, 10, 100 | Correct |
For decimals, pass a precision: 'type' => 'DECIMAL(10,2)'. WordPress accepts DECIMAL and NUMERIC with precision and scale in parentheses. Plain DECIMAL in MySQL defaults to zero decimal places, so it has the same problem.
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'price',
'value' => 49.99,
'compare' => '>',
'type' => 'DECIMAL(10,2)',
),
),
);
$query = new WP_Query( $args );
Check if a meta key EXISTS or NOT EXISTS
To find posts where a custom field exists at all, regardless of its value, use EXISTS or NOT EXISTS and leave out value:
// Posts that HAVE a 'featured_image_url' custom field
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'featured_image_url',
'compare' => 'EXISTS',
),
),
);
$query = new WP_Query( $args );
// Posts that do NOT have a 'hide_from_homepage' field
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'hide_from_homepage',
'compare' => 'NOT EXISTS',
),
),
);
$query = new WP_Query( $args );
Under the hood, EXISTS is an inner join on the meta key, and NOT EXISTS is a left join that keeps posts where no matching row was found. Two edge cases from the source: EXISTS with a value behaves exactly like =, and NOT EXISTS ignores value completely.
A field that exists but is empty still counts as existing. To find blank values, use 'compare' => '=' with 'value' => ''.
Why != skips posts without the field
This behavior is easy to miss. 'compare' => '!=' only looks at posts that have the key, so posts that never had the field are left out too. In testing, “color != red” returned the blue and green products but not the two products with no color at all. NOT IN and NOT LIKE behave the same way.
To get “anything except red, including posts with no color”, pair it with NOT EXISTS using OR:
$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'color',
'value' => 'red',
'compare' => '!=',
),
array(
'key' => 'color',
'compare' => 'NOT EXISTS',
),
),
);
Search meta values with LIKE
LIKE finds posts where a custom field contains a substring. WordPress wraps the value in % wildcards for you, so searching for “john” matches “Johnson” and “john_doe”.
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'author_name',
'value' => 'john',
'compare' => 'LIKE',
),
),
);
$query = new WP_Query( $args );
Because WordPress escapes the value first, you can’t add your own wildcards. A value of 'r%d' searches for the literal text “r%d” (in testing it matched nothing, not “red”). For “starts with” or other patterns, use REGEXP instead, for example 'value' => '^john'.
Whether LIKE is case-sensitive depends on your database collation. The default WordPress collations are case-insensitive, so “john” also matches “John”. Add 'type' => 'BINARY' when case matters. NOT LIKE excludes matches and, like !=, skips posts without the key.
How to sort posts by meta fields
Set orderby to meta_value and add a meta_key to sort by a custom field. This sorts as text:
$args = array(
'post_type' => 'page',
'order' => 'ASC',
'meta_key' => 'city_name',
'orderby' => 'meta_value',
);
$query = new WP_Query( $args );
For numbers, use meta_value_num. WordPress sorts by meta_value+0, so decimals like 9.5 sort correctly between 9 and 10:
$args = array(
'post_type' => 'product',
'meta_key' => 'price',
'orderby' => 'meta_value_num',
'order' => 'ASC',
);
$query = new WP_Query( $args );
orderby meta_value excludes posts without the meta key
Setting meta_key adds a clause that requires the key, so sorting also filters. In testing, sorting six products by color returned only the four that had a color. To sort and keep everything, use a named EXISTS clause OR NOT EXISTS, and order by the clause name:
$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'OR',
'color_clause' => array(
'key' => 'color',
'compare' => 'EXISTS',
),
array(
'key' => 'color',
'compare' => 'NOT EXISTS',
),
),
'orderby' => array(
'color_clause' => 'ASC',
'title' => 'ASC',
),
);
All six came back. Posts without a color sorted first in ascending order, since a missing value is NULL. Use DESC if you want them last.
Sort by multiple meta fields
Named clauses (supported since WordPress 4.2) are also how you sort by more than one custom field. Give each clause a string key and reference those keys in orderby:
$args = array(
'post_type' => 'product',
'meta_query' => array(
'rating_clause' => array(
'key' => 'rating',
'type' => 'NUMERIC',
),
'price_clause' => array(
'key' => 'price',
'type' => 'DECIMAL(10,2)',
),
),
'orderby' => array(
'rating_clause' => 'DESC',
'price_clause' => 'ASC',
),
);
$query = new WP_Query( $args );
This sorts by rating (highest first), then by price (lowest first) within the same rating. Sorting by a named clause uses that clause’s type for the cast, so set NUMERIC or DECIMAL or the values sort as text. Both clauses also require their keys, so products missing either field drop out.
meta_query performance
The wp_postmeta table has indexes on post_id and on meta_key (the first 191 characters), but none on meta_value, which is a longtext column. Finding rows for one key is fast. Comparing their values means scanning every row for that key, and wrapping the value in CAST() rules out any index anyway.
Things that make it worse:
- Each clause adds another join on the postmeta table, so five clauses means five joins.
- OR relations across different keys are harder for MySQL to optimize than AND.
- Sorting by a meta value forces MySQL to sort the matched rows by that value on every request.
There’s no fixed post count where it gets slow, since it depends on how many postmeta rows you have and your hosting. What helps:
- Add
'no_found_rows' => truewhen you don’t paginate, and'fields' => 'ids'when you only need IDs. - Move yes/no and category-style filters (featured, city, color) to a custom taxonomy. Taxonomy queries use indexed term tables.
- Cache the results of heavy queries with WordPress transients or an object cache.
- For sites with very large catalogs and many numeric filters, move the hot fields into a custom table with real indexes.
Frequently asked questions
What are the meta_query compare operators?
There are 17: =, !=, >, >=, <, <=, LIKE, NOT LIKE, IN, NOT IN, BETWEEN, NOT BETWEEN, EXISTS, NOT EXISTS, REGEXP, NOT REGEXP and RLIKE. The default is =, or IN when the value is an array. Any value WordPress doesn’t recognize silently becomes =.
How do I use meta_query with multiple keys?
Add one clause per key inside meta_query and set 'relation' => 'AND' (all must match) or 'relation' => 'OR' (any can match). For logic like “A AND (B OR C)”, nest a second array with its own relation. To match posts that have any one of several keys, pass an array to key.
Does orderby meta_value exclude posts without the meta key?
Yes. Setting meta_key for sorting also adds a condition that the key exists, so posts without it disappear from the results. To keep them, build an OR meta_query with a named EXISTS clause and a NOT EXISTS clause, then set orderby to the named clause.
Why does meta_query != not return posts where the field doesn’t exist?
!=, NOT IN and NOT LIKE only compare posts that have a row for the key. A post with no row isn’t “not equal”, it’s missing. Add a second clause with 'compare' => 'NOT EXISTS' and set 'relation' => 'OR' to include those posts.
What happens if I pass an empty array to meta_query IN?
WP_Meta_Query drops an empty value array, so the clause becomes “has this key” and returns every post with the field instead of none. Check the array with empty() before running the query.
Can I use meta_query with Advanced Custom Fields (ACF)?
Yes. ACF stores values in wp_postmeta, so use the field name (not the label) as the key. Date Picker fields are always saved as Ymd (like 20261231) whatever the return format, so compare against date( 'Ymd' ). Repeater sub-fields are saved under indexed keys like items_0_name, so match them with 'compare_key' => 'LIKE' on part of the key name.
Bottom line
For one field and a simple comparison, the meta_key/meta_value shorthand is fine. For anything more, use the meta_query array, set type whenever values aren’t plain text (and DECIMAL(10,2) rather than NUMERIC for decimals), and remember that negative operators and meta sorting skip posts without the key.
The full parameter reference lives in the WP_Meta_Query documentation. To set the values you’re querying, see inserting posts programmatically (its meta_input argument saves custom fields with the post), or grab a post’s ID with these post ID snippets.



4 Responses
Clear post to understand!
Thank you Andy
So happy it was helpful!
Hi, is it possible to have multiple meta_queries with AND / OR?
So I have four variables stored in custom fields, ‘user-1’, ‘user-2’ (both to be checked against current user), ‘date’ (checked against current date), ‘status’. (action/filing) and what i want to achieve in the returned posts is the following;
Result should be as follows;
Query 1 is == ‘user-1’ OR ‘user-2’ can be current user
Query 2 is == AND ‘date’ is earlier than today AND ‘status’ is (action)
I can get it to work using just one ‘user’ custom field, because then it is just three AND relations, but not to have both queried as it then feels like i have to have two meta_queries, which I don’t know is possible? I have been using Oxygen repeater with query builder to make my query rather than coding it directly. Any thoughts on the matter would be appreciated.
hi
this code don’t work!