Skip to main content
SebasVergaraP

Control engineer and full-stack WordPress developer.

A WP_Query that does not query twice

1 minute read

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.

inc/queries.php
$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_rows at 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

  1. A WP_Query that does not query twice
  2. Shipping less JavaScript than you think you need
  3. Why this theme has no cascade layers

Leave a comment

Your email address will not be published. Required fields are marked.