← All posts

WordPress WP_Query Explained: Filters, Custom Fields and Pagination Without Slowing Your Site Down

WP_Query basics, tax_query and meta_query, the pagination that returns a 404, pre_get_posts, and the settings that avoid expensive SQL queries.

WordPress WP_Query Explained: Filters, Custom Fields and Pagination Without Slowing Your Site Down

Key points

  • WP_Query can display any selection of content, but every extra query has a cost: only create one when the main query won’t do.
  • To change an archive or the search results, use pre_get_posts instead of a second query: pagination works and the site does less work.
  • no_found_rows, fields and properly typed meta queries are often enough to cut the cost of a heavy page dramatically.

“Show the three latest projects on the home page”, “list our healthcare case studies”, “a paginated news page”… Almost every dynamic layout request ends up as a WP_Query. It’s the most used tool in WordPress development, and one of the most often misused in the sites we take over: loops that break the rest of the page, pagination returning 404s, custom-field queries that drag the database down. Here’s how to use it properly, from the basics to the performance settings.

The basics: a query, a loop, a reset

A WP_Query takes an array of arguments, runs the matching SQL and gives you a loop to iterate over. The pattern never changes:

<?php
$projects = new WP_Query( [
    'post_type'      => 'project',
    'posts_per_page' => 6,
    'orderby'        => 'date',
    'order'          => 'DESC',
    'no_found_rows'  => true, // no pagination here: skip the COUNT query
] );

if ( $projects->have_posts() ) : ?>
    <ul class="projects">
    <?php while ( $projects->have_posts() ) : $projects->the_post(); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endwhile; ?>
    </ul>
<?php endif;
wp_reset_postdata(); // hand control back to the main query

First, $projects->the_post(), which sets up the globals so that the_title() or the_permalink() work. Second, wp_reset_postdata() after the loop: without it, everything that follows in the template (the rest of the page, the sidebar, some blocks) thinks it’s on the last project displayed. That’s the classic cause of a title or comment section that “switches post” at the bottom of the page.

Don’t confuse it with query_posts(), still found in old tutorials: it replaces the main query and breaks pagination and conditional tags. Don’t use it any more. And get_posts() is a handy shortcut that returns an array of post objects directly, with no_found_rows already on and suppress_filters true by default: great for a short list, but avoid it if you rely on plugins that filter queries (translation plugins, for example).

Filtering by taxonomy and custom field

The most requested filters target a category (or custom taxonomy) and a custom field, such as a year or a “featured” checkbox. tax_query and meta_query combine:

<?php
$args = [
    'post_type'      => 'project',
    'posts_per_page' => 9,
    'tax_query'      => [
        [
            'taxonomy' => 'sector',
            'field'    => 'slug',
            'terms'    => [ 'healthcare', 'manufacturing' ],
        ],
    ],
    'meta_query'     => [
        'relation' => 'AND',
        'year'    => [
            'key'     => 'delivery_year',
            'value'   => 2024,
            'compare' => '>=',
            'type'    => 'NUMERIC', // otherwise it's a string comparison: '9' > '10'
        ],
        [
            'key'     => 'featured',
            'value'   => '1',
        ],
    ],
    'orderby'        => [ 'year' => 'DESC', 'title' => 'ASC' ], // sort on the named clause
];
$projects = new WP_Query( $args );

The traps we run into most often:

  • Forgetting 'type' => 'NUMERIC' (or DATE). Meta values are stored as text: without a type, the comparison is alphabetical and “9” sorts after “10”.
  • Filtering a taxonomy-like value with meta_query. If a piece of data is used to filter and group (sector, city, service type), it’s a taxonomy, not a custom field: term queries are indexed, meta queries much less so.
  • Sorting by a field without naming the clause. With an associative array ('year' => [...]) you can sort directly on that clause in orderby, avoiding the meta_key / orderby => meta_value_num pair, which silently drops posts without a value.
  • ACF relationship or multi-checkbox fields are stored as serialised arrays: compare => '=' won’t find them. You need a LIKE on the quoted value, slow by nature, or better, a different structure (a taxonomy or a dedicated relationship).

Pagination returning a 404 (and pre_get_posts)

A paginated list built on a custom query needs two things: pass the page number, and use your query’s page count.

<?php
// On a static front page, WordPress uses 'page', not 'paged'
$paged = max( 1, (int) get_query_var( 'paged' ), (int) get_query_var( 'page' ) );

$news = new WP_Query( [
    'post_type'      => 'post',
    'posts_per_page' => 10,
    'paged'          => $paged,
] );

// ... loop ...

echo paginate_links( [
    'total'   => $news->max_num_pages,
    'current' => $paged,
] );
wp_reset_postdata();

That works on a static page. On an archive (a category, a post type archive), however, page 2 often returns a 404. The reason: WordPress decides on the 404 before your template runs, based on the main query. If that one shows 10 posts per page and your secondary query shows 6, the last pages don’t exist as far as WordPress is concerned.

The right fix isn’t a second query but changing the main one with pre_get_posts:

<?php
// Change the main query instead of running a second one
add_action( 'pre_get_posts', function ( WP_Query $q ) {
    if ( is_admin() || ! $q->is_main_query() ) {
        return; // never touch the admin or secondary queries
    }
    if ( $q->is_post_type_archive( 'project' ) ) {
        $q->set( 'posts_per_page', 12 );
        $q->set( 'orderby', 'menu_order' );
        $q->set( 'order', 'ASC' );
    }
    if ( $q->is_search() ) {
        $q->set( 'post_type', [ 'post', 'page', 'project' ] );
    }
} );

The archive template keeps its standard loop (have_posts() / the_post()), native pagination works, and the database runs one query instead of two. On sites we take over, replacing doubled-up queries with a pre_get_posts hook is one of the best-value optimisations, and it gets rid of pagination 404s along the way. Mind the guard clause: without is_main_query() and ! is_admin(), your hook would also alter menus, widgets and admin list screens.

Fast queries: the settings that matter

By default WP_Query does more than you need: it counts the total number of results for pagination, and loads every meta value and term for the posts it finds. For an unpaginated list or internal processing, switch off what you don’t use:

<?php
// IDs only, no pagination, no meta loading
$ids = new WP_Query( [
    'post_type'              => 'project',
    'posts_per_page'         => 200,
    'fields'                 => 'ids',
    'no_found_rows'          => true,
    'update_post_meta_cache' => false,
    'update_post_term_cache' => false,
] );

// Excluding the current post from a "read next" block: filter in PHP
// rather than with post__not_in, which makes the query harder to cache
$links = array_slice( array_diff( $ids->posts, [ get_the_ID() ] ), 0, 3 );
  • no_found_rows => true skips the total count: turn it on whenever there’s no pagination.
  • fields => 'ids' only fetches IDs: ideal for processing, exports or feeding another query.
  • posts_per_page => -1 is a no-go on content that grows: the page showing 30 projects today will load 3,000 in three years. Set a limit, even a high one.
  • Multiple meta_query clauses each add a join on the postmeta table. Beyond two or three, measure: a taxonomy or a dedicated field is often a better fit.

To measure, the Query Monitor plugin shows every SQL query, its duration and the code that triggered it. It’s the first tool we install on staging for a slow site. If an expensive query runs on every page (a “latest projects” block in the footer, say), cache its result in a transient or the object cache, and clear it when content of that type is published.

FAQ

Why does my query show nothing at all?

First check the post_type (the exact slug of the content type), then test the arguments one at a time: a single badly typed filter is enough to exclude everything. Remember that logged-out visitors only see published content.

Should I use WP_Query inside a Gutenberg block?

For a simple list, the core Query Loop block is often enough and stays editable by the client. For custom logic, a dynamic block whose render.php runs a WP_Query is the right approach.

WP_Query or a direct SQL query with $wpdb?

WP_Query in almost every case: it respects statuses, permissions, caching and plugins. $wpdb makes sense for aggregates (sums, statistics) or custom tables, always with $wpdb->prepare().

A WordPress site to extend, slow listing pages or pagination that stopped working? We build and optimise custom themes and plugins with clean, maintainable code.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →