Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 68 ยท The Database and the Loop

WP_Query in Depth

Learn WP_Query - arguments like post_type, posts_per_page, orderby, s, author, date_query and post__in, found_posts, max_num_pages, wp_reset_postdata and no_found_rows.

WP_Query is the class that fetches posts. The main query that runs before every page is a WP_Query, and whenever you need extra posts, such as "three related articles" or "upcoming events", you create your own. You pass it an array of arguments that describe the posts you want, and it builds the SQL, runs it and keeps the results ready for the Loop.

This lesson covers the arguments you will use daily, how pagination numbers work, the difference between WP_Query and get_posts(), and the one performance flag that most developers forget. Meta and taxonomy filters get their own lesson: meta queries and taxonomy queries.

WordPress cannot run here. The real WP_Query code is read-only, and the runnable example is a small stand-in over SQLite that honors a subset of the arguments. It shows the idea (arguments in, SQL out), not WordPress's real internals.

A custom query, step by step

A custom query follows a fixed pattern: create it, loop over it, then reset the global post data.

PHP
<?php
$recent = new WP_Query( [
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => 3,
    'orderby'        => 'date',
    'order'          => 'DESC',
] );

if ( $recent->have_posts() ) {
    while ( $recent->have_posts() ) {
        $recent->the_post();
        ?>
        <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
        <?php
    }
    wp_reset_postdata();
} else {
    echo '<p>No posts yet.</p>';
}

Two points are easy to miss. First, you call have_posts() and the_post() on your object ($recent->), not the global functions, because the global functions work on the main query. Second, wp_reset_postdata() restores the global $post that the_post() replaced. Run it after every secondary loop.

flowchart LR
    A["Arguments array"] --> B["WP_Query"]
    B --> C["SQL against wp_posts"]
    C --> D["Post objects"]
    D --> E["Loop: have_posts / the_post"]
    B --> F["found_posts and max_num_pages"]

WP_Query turns an arguments array into SQL, and exposes both the posts and the totals.

The arguments you will use most

Argument Example Meaning
post_type 'page', ['post', 'book'] Which kind of content. Default is post.
post_status 'publish', 'draft' Default is publish (plus private posts the user may read).
posts_per_page 10, -1 How many per page. -1 means all, which is risky on large sites.
paged 2 Which page of results to return.
orderby 'date', 'title', 'rand', 'post__in' The sort field. Default is date.
order 'ASC', 'DESC' Direction. Default is DESC.
s 'hooks' A search term, matched against title and content.
author 4 Posts by one author ID. author_name uses the login slug.
post__in [5, 9, 12] Only these IDs. post__not_in excludes them.
date_query see below Filter by publish date.

Some arguments take other types than you might expect. posts_per_page => -1 returns everything, 'orderby' => 'post__in' keeps the order you gave in the post__in array, and author__in takes an array of IDs.

Date queries

date_query is a list of conditions. Each one says "after", "before" or an exact year, month or day:

PHP
<?php
$q = new WP_Query( [
    'post_type'  => 'post',
    'date_query' => [
        [
            'after'     => '2025-01-01',
            'before'    => '2025-06-30',
            'inclusive' => true,
        ],
    ],
] );

You can also use 'year' => 2025, 'monthnum' => 3, and 'column' lets you filter on post_modified instead of the publish date.

found_posts and max_num_pages

After a query runs, the object tells you how many posts matched in total, not just how many are on this page:

  • $q->post_count is the number of posts in this page of results.
  • $q->found_posts is the number of posts that match the arguments across all pages.
  • $q->max_num_pages is ceil( found_posts / posts_per_page ).

To get found_posts, WordPress asks MySQL for the total with an extra count query (it adds SQL_CALC_FOUND_ROWS or a separate COUNT query, depending on the version). That is useful for pagination links, but it costs time on large tables.

Pagination and no_found_rows

If you only need the first few posts and do not draw page links, tell WordPress to skip the total:

PHP
<?php
$latest = new WP_Query( [
    'posts_per_page' => 5,
    'no_found_rows'  => true,
] );

With no_found_rows => true, found_posts and max_num_pages stay at zero, and the count query never runs. Use it for sidebars, "related posts" blocks and anything that shows a fixed number of items without paging. Leave it off whenever you print page links, because they need the totals.

For a paginated custom query, you pass the current page yourself:

PHP
<?php
$paged = max( 1, (int) get_query_var( 'paged' ) );

$q = new WP_Query( [
    'post_type'      => 'book',
    'posts_per_page' => 6,
    'paged'          => $paged,
] );

// ... the Loop ...

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

A mini WP_Query you can run

This stand-in accepts a handful of arguments and turns them into a prepared SQL statement over an in-memory SQLite table shaped like wp_posts. It also computes found_posts and max_num_pages unless no_found_rows is set. The real class does much more, but the core move is the same: arguments in, SQL out.

PHP A mini WP_Query over SQLite

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.

Look at the last line of the output. The stand-in builds its WHERE clause from the arguments and uses placeholders for every value, so a search term can never break out of the SQL. Real WP_Query does the same through $wpdb->prepare(). The final example sets no_found_rows, so its totals stay at zero, just as the real class behaves.

get_posts() versus WP_Query

get_posts() is a shortcut for "just give me an array of post objects":

PHP
<?php
$books = get_posts( [
    'post_type'   => 'book',
    'numberposts' => 5,
    'orderby'     => 'title',
    'order'       => 'ASC',
] );

foreach ( $books as $book ) {
    echo esc_html( $book->post_title );
}

Internally it creates a WP_Query with no_found_rows set to true and a few cache flags changed, then returns $query->posts. Compare the two:

get_posts() new WP_Query()
Returns An array of WP_Post objects A query object
Totals (found_posts) Not available Available unless no_found_rows
Pagination Awkward Built in
Loop functions Need setup_postdata() by hand have_posts() and the_post() work
Best for Simple lists, IDs, quick data access Anything displayed as a full Loop or paginated list

Use get_posts() with 'fields' => 'ids' when you only need IDs. Use WP_Query when you want to loop and use template tags.

Common mistakes

  • posts_per_page => -1 on big sites. It loads every matching post into memory. Set a sensible limit.
  • Forgetting wp_reset_postdata(). The global $post stays on the last item of your loop.
  • Using query_posts(). It replaces the main query and breaks pagination. Never use it; see the main query lesson.
  • Querying inside a loop. A new WP_Query per post can multiply database work. Fetch what you need once, before the loop.
  • Ignoring no_found_rows. If you never print page links, set it to true.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call restores the global $post after a secondary WP_Query loop?

    wp_reset_postdata() puts the global $post back to the page's own post after your custom loop has changed it.
  2. 2. What does 'no_found_rows' => true do?

    The extra count query for pagination totals is skipped, which saves time when you do not draw page links.
  3. 3. With 25 matching posts and 'posts_per_page' => 10, what is max_num_pages?

    max_num_pages is ceil(found_posts / posts_per_page), here ceil(25 / 10) = 3.
  4. 4. Which statement about get_posts() is true?

    get_posts() wraps WP_Query with no_found_rows enabled and returns the posts array only.

Summary

  • new WP_Query( $args ) fetches posts from an arguments array; call have_posts() and the_post() on your own object.
  • Always call wp_reset_postdata() after a secondary loop.
  • Core arguments include post_type, posts_per_page, paged, orderby, order, s, author, post__in and date_query.
  • found_posts and max_num_pages describe all matches; no_found_rows => true skips that work when you do not paginate.
  • get_posts() is a quick wrapper that returns an array without totals.
  • The runnable example is a plain-PHP stand-in over SQLite, not the real class.

Next: Meta Queries and Taxonomy Queries