Almost every WordPress theme and plugin uses WP_Query to fetch posts, pages, products and custom content. It’s flexible, well documented and easy to use. It’s also behind many of the slow pages I diagnose.
The problem isn’t WP_Query itself. It’s that its default behaviour does more work than many queries need, and some parameters that look harmless trigger very expensive database operations on large sites. A query that’s instant with 50 posts can take seconds with 50,000.
Here’s how I write WP_Query calls that stay fast as sites grow.
Understand what WP_Query does by default
When you run a basic query, WordPress does more than fetch matching posts:
- It runs a query to count the total matching posts, so pagination can be calculated.
- It loads post metadata for all returned posts into the cache.
- It loads taxonomy terms for all returned posts into the cache.
- It builds full post objects.
For a main blog archive with pagination, that’s all useful. For a sidebar widget showing five recent post titles, most of it is wasted.
Skip the count when you don’t paginate
The total count uses SQL_CALC_FOUND_ROWS or a separate count query, which can be expensive on large tables. If you’re not displaying pagination, turn it off:
no_found_rows is one of the simplest and most effective performance improvements for secondary queries, like related posts, recent posts and featured items.
Don’t load what you won’t use
If you won’t use post meta or terms from the returned posts, skip loading them into the cache:
Be careful: if your template later calls get_post_meta or displays categories for these posts, WordPress will run separate queries for each post instead, which is slower. Only disable these caches when you really don’t need the data.
Fetch only IDs when that’s all you need
If you need a list of post IDs, for example to pass to another function or check counts, request only IDs:
This avoids building full post objects and uses less memory.
Avoid unlimited queries
posts_per_page set to -1 returns every matching post. It looks convenient, but on a growing site, it eventually returns thousands of rows, using huge amounts of memory and time. I’ve seen pages run out of memory because of a single unlimited query in a menu or footer widget.
Always set a sensible limit. If you genuinely need to process every post, do it in batches, ideally in a background task or WP-CLI command rather than during a page load:
Be careful with meta queries
Meta queries filter or sort by custom field values. They’re powerful, but the postmeta table is designed as a flexible key-value store, not for fast filtering. Meta values aren’t indexed for searching, so meta queries on large sites can be slow.
Problems get worse with:
- Multiple meta conditions in one query, each adding a join.
- OR relations between meta conditions.
- LIKE comparisons on meta values.
- Ordering by meta values on large result sets.
- Comparing numeric values stored as strings, which also gives wrong ordering.
Ways to improve:
- Use taxonomies for filtering. If you filter by something like a category, type or status, a taxonomy query performs much better than a meta query.
- Store values in the right format, and specify the type, like NUMERIC or DATE, in meta queries for correct comparisons.
- Reduce the number of conditions.
- Cache results of expensive queries.
- Consider custom tables for structured data that’s queried heavily, like large datasets with filtering.
Avoid orderby rand
Random ordering looks innocent:
But it forces the database to assign a random value to every matching row and sort them all, then return a few. On large tables, it’s very slow, and it also defeats caching, since results change every time.
Alternatives:
- Fetch a larger set of recent or popular IDs, cached, and pick randomly in PHP.
- Pre-compute random selections periodically and store them in a transient.
- Rotate featured items on a schedule instead of on every page load.
Use tax queries sensibly
Taxonomy queries are usually efficient, but complex combinations with many terms and nested relations can still be costly. Keep tax queries focused, and use include_children deliberately; including children of hierarchical terms adds more terms to the query.
Limit post statuses and types
Be explicit about what you query. Querying post_type any or many post statuses scans more data than necessary. Ask for exactly the post types and statuses you need.
Avoid queries in loops
One of the most common performance problems is running queries inside loops, sometimes called the N plus one problem. For example, running a query for each post in a list to fetch related data. With 20 posts, that’s 21 queries; with 100, it’s 101.
Instead:
- Fetch related data in bulk before the loop.
- Rely on WordPress’s meta and term caches, which load data for all posts in one query when update_post_meta_cache and update_post_term_cache are enabled.
- Cache results.
Query Monitor makes these patterns easy to spot, showing duplicate queries and which component triggered them.
Modify the main query instead of adding a second one
A common mistake on archive pages is running a custom WP_Query in the template while ignoring the main query WordPress already ran. That doubles the work.
To change what an archive shows, modify the main query with pre_get_posts:
Always check is_main_query and is_admin, so you don’t accidentally change other queries or admin screens.
Cache expensive query results
For queries that are expensive and don’t change often, cache the results:
With a persistent object cache like Redis, these cached results persist between requests. Without one, use transients for data that should persist. Clear or refresh the cache when relevant content changes, for example on save_post.
Use the right function
- WP_Query for full control and loops.
- get_posts for simple lists; it sets no_found_rows and suppress_filters by default.
- Direct database queries with $wpdb only when WP_Query genuinely can’t do what you need, always with prepare.
Note that get_posts suppresses filters by default, which can matter for plugins that modify queries, like multilingual plugins.
Measure
Use Query Monitor to see the actual SQL WP_Query generates, how long it takes and how many queries a page runs. Test queries with realistic data volumes, not just a handful of sample posts. A query that’s fine in development can be a disaster in production.
A real example of query problems
On one site I audited, the homepage took several seconds to generate uncached. Query Monitor showed over three hundred database queries. The theme’s “featured services” section ran a meta query with an OR relation across three fields, the footer listed every published post with posts_per_page set to -1, and a related posts widget ran a separate query for each of twenty posts. None of these looked dangerous in the code, and all had been fine when the site had a few dozen posts.
Fixing them took an afternoon: a taxonomy replaced the meta query, the footer list was limited and cached, and related posts were fetched in a single query. The homepage went from hundreds of queries to a few dozen, and generation time dropped dramatically. The lesson is that queries need to be written for the size the site will become, not the size it is at launch.
Review queries during code reviews
When reviewing theme or plugin code, look specifically for unlimited queries, meta queries, random ordering and queries inside loops. Catching them in review is far cheaper than discovering them when the site slows down.
Test with production-sized data
Before launching new templates, test them against a copy of production data, or generate realistic volumes of test content. Queries that fly with ten posts can crawl with ten thousand.
Fast queries are one of the cheapest performance wins available.
Frequently asked questions
What’s the easiest WP_Query performance win?
Adding no_found_rows to queries that don’t need pagination, and replacing posts_per_page -1 with sensible limits.
Are meta queries always slow?
Not always, but they scale poorly on large postmeta tables, especially with multiple conditions or LIKE comparisons. Use taxonomies for filtering where possible.
Should I use get_posts or WP_Query?
Use get_posts for simple retrieval and WP_Query for loops, pagination and when you need more control. Both use the same underlying query engine.
How do I find slow queries?
Use Query Monitor on affected pages and the database slow query log on the server.
Final thoughts
Efficient queries keep WordPress fast as content grows. Skip counts you don’t need, load only the data you’ll use, avoid unlimited and random queries, prefer taxonomies over meta queries for filtering, avoid queries inside loops, modify the main query instead of duplicating it and cache expensive results. Measure with realistic data. Small changes in how you query can make the difference between a page that loads instantly and one that grinds.




