Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 68 ยท The Database and the Loop

The Main Query and pre_get_posts

Understand the WordPress main query - why query_posts() is wrong, how pre_get_posts and is_main_query() change archives safely, conditional tags and pagination.

Every front-end page starts with a query you did not write. When someone visits /category/news/page/2/, WordPress reads the URL, works out that it is a category archive on page 2, and builds a WP_Query for it. That is the main query. Your template's Loop just prints its results.

Often you want to change that query: show 12 posts instead of 10 on the home page, include a custom post type in search results, or sort an archive by title. This lesson shows the right way, the pre_get_posts action, and the wrong way, query_posts(). It also covers the conditional tags that tell you which page you are on, and the functions that print pagination.

The real hook code is shown in read-only blocks. The runnable examples use a small plain-PHP stand-in for hooks and query objects. They illustrate the pattern and are not WordPress itself. If hooks are new to you, the actions and filters lesson goes deeper.

Why not query_posts()

You will see old tutorials that write this in a template:

PHP
<?php
// Do NOT do this.
query_posts( 'posts_per_page=5&cat=3' );

query_posts() throws away the main query and runs a new one, after WordPress has already queried once. That costs an extra database query, and it replaces the global $wp_query, which breaks pagination, conditional tags and any plugin that expected the original.. The correct tool changes the main query before it runs.

pre_get_posts

pre_get_posts is an action that fires after WordPress has built the query object from the URL, but before it asks the database. Your callback receives the WP_Query by reference, so you can change its settings with set():

PHP
<?php
add_action( 'pre_get_posts', 'myprefix_tweak_main_query' );

function myprefix_tweak_main_query( WP_Query $query ): void {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }

    if ( $query->is_home() ) {
        $query->set( 'posts_per_page', 12 );
    }

    if ( $query->is_search() ) {
        $query->set( 'post_type', [ 'post', 'book' ] );
    }
}

The hook fires for every WP_Query created during the request: the main one, widgets, your own secondary loops, and admin screens. That is why the first lines are guards:

  • is_admin() is true inside wp-admin. Without this check, you would change post lists in the admin, too.
  • $query->is_main_query() is true only for the page's main query. Without it, your change leaks into every secondary query.

Use the methods on $query ($query->is_home()) rather than the global conditional functions (is_home()), because inside pre_get_posts the global query may not be set up yet.

sequenceDiagram
    participant W as WordPress
    participant Q as Main WP_Query
    participant H as pre_get_posts callbacks
    participant D as Database
    W->>Q: Build query from URL
    Q->>H: do_action pre_get_posts
    H-->>Q: set(posts_per_page, 12)
    Q->>D: Run SQL
    D-->>Q: Rows
    Q-->>W: Posts ready for the Loop

Your callback runs between building the query from the URL and running the SQL.

A stand-in you can run

The stand-in below has a tiny hook registry, a MiniQuery with set() and is_main_query(), and an is_admin() flag. It creates one main query and one secondary query, fires pre_get_posts for both, and shows which one the callback changed.

PHP Altering the main query with a pre_get_posts stand-in

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.

Only the first two lines changed. The widget's secondary query and the admin screen were protected by the guards. Remove the is_main_query() check mentally and imagine the widget showing 12 posts too: that is the bug people hit when they forget the guard.

Conditional tags

Conditional tags answer "what kind of page is this?". They return booleans, and they read the main query's flags. These are the ones you will use most:

Tag True when
is_front_page() The site's front page, whether it shows posts or a static page.
is_home() The blog posts index. This is the front page only if the site shows latest posts.
is_single() A single post of any type except pages and attachments.
is_page() A single page.
is_singular() Any single post, page or custom post type.
is_archive() Any archive: category, tag, author, date, custom post type, taxonomy.
is_category(), is_tag(), is_tax() A category, tag or custom taxonomy archive. is_tax( 'genre' ) targets one taxonomy.
is_author(), is_date() Author and date archives.
is_search() Search results.
is_404() Not found.
is_paged() Page 2 or later of any listing.

is_home() versus is_front_page() is the most confused pair. If a site has "Your homepage displays: a static page" in the settings, the front page is that page and is_home() is true for the page set as the posts page instead.

Most of these also accept arguments. is_category( 'news' ) is true for the category with the slug, ID or name news, and is_singular( [ 'book', 'movie' ] ) checks several types.

Conditional tags are only reliable after the main query has run, which means from the wp action onward, and inside templates. Calling them on init returns false because nothing has been queried yet.

Pagination functions

When a listing has more than one page, templates print navigation with built-in functions:

PHP
<?php
// Previous and next links, using the main query.
the_posts_navigation();

// Numbered pagination.
the_posts_pagination( [
    'mid_size'  => 2,
    'prev_text' => 'Newer',
    'next_text' => 'Older',
] );

// Lower level, also works for custom queries.
echo paginate_links( [
    'total'   => $custom_query->max_num_pages,
    'current' => max( 1, get_query_var( 'paged' ) ),
] );

the_posts_navigation() and the_posts_pagination() read max_num_pages from the main query, so they work after a pre_get_posts change automatically. For a secondary query, use paginate_links() with the totals from your own object (see WP_Query in depth).

PHP Conditional tags and pagination from query flags

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.

The real conditional tags check many more query flags, but the idea is identical: the URL becomes query variables, the variables set boolean flags, and the tags read the flags.

Practical recipes

Sort an archive of a custom post type alphabetically:

PHP
<?php
add_action( 'pre_get_posts', function ( WP_Query $query ): void {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }
    if ( $query->is_post_type_archive( 'book' ) ) {
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' );
        $query->set( 'posts_per_page', 24 );
    }
} );

Exclude a category from the blog index:

PHP
<?php
add_action( 'pre_get_posts', function ( WP_Query $query ): void {
    if ( ! is_admin() && $query->is_main_query() && $query->is_home() ) {
        $query->set( 'category__not_in', [ 7 ] );
    }
} );

Remember that you can set any argument that WP_Query accepts, including meta_query and tax_query from the previous lesson.

Common mistakes

  • No guards. Without is_admin() and is_main_query(), you alter admin screens, widgets and REST requests.
  • Using global conditional tags inside pre_get_posts. Use $query->is_home() and friends.
  • Setting posts_per_page on a REST or feed request by accident. Add a condition like $query->is_home() so only the intended pages change.
  • Using query_posts(). Replace it with pre_get_posts for the main query or new WP_Query for an extra list.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is query_posts() discouraged?

    query_posts() discards the main query and issues a new one, which costs extra database work and confuses later code that expects the original query.
  2. 2. When does the pre_get_posts action fire?

    It fires after WordPress parses the URL into query variables and before the query is executed, for every WP_Query object created.
  3. 3. What does the $query->is_main_query() check protect you from?

    pre_get_posts runs for every query. The check restricts your change to the page's own main query.
  4. 4. A site shows a static front page and a separate Blog page. Which tag is true on the Blog page?

    is_home() means the blog posts index, which is the page assigned as the posts page. is_front_page() is true on the static page assigned as the front page.

Summary

  • The main query is built from the URL before your template runs; the Loop prints its results.
  • Change it with the pre_get_posts action and $query->set(), never with query_posts().
  • Always guard with is_admin() and $query->is_main_query(), and use the $query->is_*() methods inside the callback.
  • Conditional tags such as is_home(), is_single(), is_archive() and is_tax() read flags from the main query and are reliable from the wp action onward.
  • the_posts_pagination() and paginate_links() print page links from max_num_pages.
  • The runnable examples are plain-PHP stand-ins that show the pattern, not WordPress code.

Next: The Template Hierarchy