A WP_Query that does not query twice
Secondary queries in a theme are usually copied from somewhere else, flags and all. Three of those flags do something real, and one of them is a trap.
The flag that matters
no_found_rows drops the extra SQL_CALC_FOUND_ROWS bookkeeping. If you are not paginating the result, you are paying for a total you will never read.
$query = new WP_Query(
array(
'post_type' => 'post',
'posts_per_page' => 3,
'ignore_sticky_posts' => true,
'no_found_rows' => true,
)
);
When not to use it
As soon as you paginate. The moment the template calls the_posts_pagination(), it needs a total, and suppressing the count means the pagination quietly renders wrong rather than loudly failing.
- Paginated archive: leave
no_found_rowsat its default. - Fixed-count sidebar or front-page list: turn it on.
- Anything you are about to loop twice: rethink the query instead.
Part of a series
Part 1 of 3 in Building this theme
- A WP_Query that does not query twice
- Shipping less JavaScript than you think you need
- Why this theme has no cascade layers