Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 68 ยท The Database and the Loop

Meta Queries and Taxonomy Queries

Learn WP_Query meta_query and tax_query - compare operators, types, relation, nested groups, the performance cost of meta queries, and orderby meta_value_num.

Posts are rarely selected by title alone. You want "events that cost less than 20" or "articles in the Tutorials category that are not tagged beginner". WordPress stores that information in two places, post meta (wp_postmeta) and terms (the taxonomy tables), and WP_Query has one argument for each: meta_query and tax_query.

Both take an array of clauses that you can combine with AND and OR and nest as deeply as you need. This lesson explains the clause options, then builds a small SQL generator so you can see what such arrays turn into. It also covers the thing that matters most in production: meta queries are easy to write and expensive to run. The tables involved are described in the database schema, and the basics of the query class are in WP_Query in depth.

Real WordPress code appears in read-only blocks. The runnable examples are plain-PHP stand-ins over SQLite. Real WP_Query joins the meta table once per clause instead of using the EXISTS subqueries shown here, but the meaning of the arrays is the same.

Meta queries

A meta_query is a list of clauses. Each clause describes one condition on one meta key:

PHP
<?php
$q = new WP_Query( [
    'post_type'  => 'event',
    'meta_query' => [
        'relation' => 'AND',
        [
            'key'     => 'price',
            'value'   => [ 10, 30 ],
            'compare' => 'BETWEEN',
            'type'    => 'NUMERIC',
        ],
        [
            'key'     => 'featured',
            'value'   => '1',
            'compare' => '=',
        ],
    ],
] );

The keys of a clause:

Key Meaning
key The meta key, such as price.
value What to compare to. An array for IN, NOT IN and BETWEEN.
compare = (default), !=, >, >=, <, <=, LIKE, NOT LIKE, IN, NOT IN, BETWEEN, NOT BETWEEN, EXISTS, NOT EXISTS, REGEXP and friends.
type How to treat the stored text: CHAR (default), NUMERIC, DECIMAL, DATE, DATETIME, TIME, SIGNED, UNSIGNED, BINARY.

Meta values are stored as text (longtext) in the database. Without a type, comparisons are text comparisons, so '9' > '100' is true. Whenever you compare numbers or dates, set the type. For EXISTS and NOT EXISTS, you leave value out.

The relation key sets how the clauses combine, AND (the default) or OR. A clause that is itself an array of clauses is a nested group, with its own relation:

PHP
<?php
'meta_query' => [
    'relation' => 'AND',
    [ 'key' => 'featured', 'compare' => 'EXISTS' ],
    [
        'relation' => 'OR',
        [ 'key' => 'price', 'value' => 50, 'compare' => '>=', 'type' => 'NUMERIC' ],
        [ 'key' => 'city',  'value' => 'Oslo' ],
    ],
],

That reads as: featured exists AND (price is at least 50 OR city is Oslo).

flowchart TD
    A["relation: AND"] --> B["featured EXISTS"]
    A --> C["relation: OR"]
    C --> D["price >= 50 (NUMERIC)"]
    C --> E["city = Oslo"]

Meta clauses form a tree: each group has a relation, each leaf is one condition.

Seeing meta queries as SQL

The stand-in below turns the same arrays into SQL and runs them against SQLite tables that mirror wp_posts and wp_postmeta. It handles relation, nesting, compare operators and the NUMERIC type. Notice the third query: the same condition gives different results when the type changes.

PHP Generating SQL from a meta_query array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Query C is the classic trap. As text, '9' > '20' is true because '9' sorts after '2', so the cheap poetry slam sneaks into the results. As numbers, it is correctly excluded. In WordPress, setting 'type' => 'NUMERIC' casts the stored value so the database compares numbers.

Sorting by meta

To order posts by a meta value, set meta_key and use orderby:

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

meta_value_num sorts numerically and meta_value sorts as text. Setting meta_key also acts as a filter: posts without that key are dropped. When you already have a meta_query, you can give a clause a name and order by it, for example 'price_clause' => [ 'key' => 'price', 'type' => 'NUMERIC' ] together with 'orderby' => 'price_clause'.

Taxonomy queries

A tax_query selects posts by terms. The structure matches meta_query:

PHP
<?php
$q = new WP_Query( [
    'post_type' => 'post',
    'tax_query' => [
        'relation' => 'AND',
        [
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => [ 'tutorials', 'news' ],
            'operator' => 'IN',
        ],
        [
            'taxonomy' => 'post_tag',
            'field'    => 'slug',
            'terms'    => 'beginner',
            'operator' => 'NOT IN',
        ],
    ],
] );
Key Meaning
taxonomy The taxonomy name: category, post_tag or your own.
field How you identify terms: term_id (default), slug, name or term_taxonomy_id.
terms One value or an array.
operator IN (default): any of the terms. NOT IN: none of them. AND: all of them. EXISTS and NOT EXISTS: has any or no term in the taxonomy.
include_children For hierarchical taxonomies, whether child terms count too (default true).

The default field is the numeric term ID, which is fast and stable. Slugs are friendlier in code but can be renamed by an editor.

Simple category and tag filters also have shortcuts: cat, category_name, tag, tag__in. Use tax_query when you need custom taxonomies or combinations.

PHP Generating SQL from a tax_query array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the difference between IN and AND on the same terms: IN means "any of these", AND means "every one of these". The last query shows that groups can nest, exactly as in meta_query.

The cost of meta queries

Meta and taxonomy queries are not equally cheap. Here is why meta queries need care:

  • wp_postmeta is an EAV table (entity, attribute, value). Every post has many rows, and one site can have millions.
  • Each clause adds another join on that table. Three clauses mean three joins.
  • meta_value is longtext and WordPress indexes only post_id and the first 191 characters of meta_key. Nothing indexes the value, so MySQL cannot jump to "price over 20". It examines every row for the key.
  • Numeric and date comparisons require a cast, which prevents using any index on the value even if you added one.
  • OR relations and LIKE '%text%' make it worse.

Taxonomy queries join through indexed term tables and scale much better. Practical advice:

  1. Use taxonomies for things you filter on. "Status", "genre" and "level" are better as terms than as meta values.
  2. Keep meta queries to one or two clauses and always combine them with a narrow post_type and a posts_per_page limit.
  3. Store dates in a sortable format, such as YYYYMMDD or Y-m-d, and use type => 'DATE' or NUMERIC.
  4. Cache the result of heavy queries with a transient (see the Options API and transients).
  5. Consider a custom table when you filter or sort on a value across large amounts of data. See $wpdb and custom tables.
  6. Measure. Query Monitor shows each query and how long it took; see debugging WordPress.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a numeric meta comparison include 'type' => 'NUMERIC'?

    wp_postmeta stores values as text. The type makes the database cast the value before comparing, so numbers compare as numbers. It does not change stored data.
  2. 2. In a tax_query clause, what does 'operator' => 'AND' with two terms mean?

    IN means any of the terms, NOT IN means none, and AND means every listed term must be assigned.
  3. 3. How do you express "featured exists AND (price >= 50 OR city = Oslo)" in a meta_query?

    Clauses can be nested arrays with their own relation, which lets you build any AND/OR tree.
  4. 4. Which is the best advice for fields you filter on across thousands of posts?

    Term tables are indexed and cheap to join, while meta values are unindexed text. A custom table is the answer for large numeric or date filtering.

Summary

  • meta_query filters by post meta and tax_query by terms; both are lists of clauses with an optional relation and nested groups.
  • A meta clause has key, value, compare and type. Set type for numbers and dates, because values are stored as text.
  • Sort by meta with meta_key plus orderby => 'meta_value_num' (numbers) or meta_value (text).
  • Tax clauses use taxonomy, field, terms and operator (IN, NOT IN, AND, EXISTS, NOT EXISTS).
  • Meta queries join an unindexed EAV table once per clause, so keep them small, narrow and cached.
  • The runnable examples are plain-PHP SQL generators, not the real implementation.

Next: The Main Query and pre_get_posts