Plugins Plugin hub Backup SEO Caching Security Forms WooCommerce Images Best backup plugins
Hosting Hosting directory Shared hosting Managed WordPress Cloud hosting VPS hosting By reader location Hosting finder
Themes & builders Compare Rank Math vs Yoast
Tools All tools Hosting finder Plugin stack builder Cost calculator Salt generator Theme detector Who is hosting this? Speed test Headline analyzer robots.txt generator Redirect generator Uptime calculator Blog name generator
Blog Best backup plugins Deals
Guides All guides Speed up WordPress Choose hosting Back up WordPress
How we test

Developer · Explainer

What Is Query in WordPress? Explained

What Is Query in WordPress? Explained

Short answer

A query in WordPress is a request for content from the database, such as the latest posts or one specific page. WordPress runs a main query for every URL using the WP_Query class, then your theme displays the results with the Loop or a Query Loop block.

Key takeaways

  • A query fetches posts from the database for each page view.
  • The main query runs automatically based on the URL.
  • WP_Query is the PHP class behind post queries, including custom ones.
  • The Loop displays posts, and the Query Loop block does it without code.
  • Use pre_get_posts to change the main query instead of adding new queries.
  • Heavy or numerous queries slow pages, so measure them with a debugging plugin.

What is a query in WordPress?

A query in WordPress is a request for content from the database, such as the latest 10 posts or the page with this URL, which WordPress then shows using your theme's templates.

Every page view starts with a query. When someone visits a URL, WordPress works out what they asked for, fetches matching posts from the database, and hands them to the theme.

The word covers a few related ideas, which is why it can be confusing:

TermWhat it means
Main queryThe query WordPress runs automatically for each URL
WP_QueryThe PHP class that builds and runs post queries
Custom queryAn extra WP_Query you create for a specific section
Query varsThe parameters, such as category or page number, that shape a query
Query Loop blockA block editor tool that displays posts from a query
Database queryA raw SQL request to the database, often through $wpdb

Most of the time, query means a post query built with WP_Query. The rest of this guide explains each piece.

What is the main query?

The main query is the query WordPress runs on its own for every page load, based on the URL, and it decides which posts the page shows and which template is used.

When you visit a category archive, the main query fetches posts in that category. On a single post URL, it fetches that one post. On the homepage, it fetches your latest posts or your static front page.

WordPress builds the main query in a few steps:

  1. It reads the URL and matches it against rewrite rules.
  2. It turns the URL into query vars, such as category_name=news or p=42.
  3. It passes those vars to WP_Query, which runs SQL against the database.
  4. It uses the result to pick a template from the template hierarchy.

The results are stored in a global object called $wp_query. Theme templates loop through it to display content.

What is WP_Query?

WP_Query is the PHP class WordPress uses to fetch posts; you give it arguments like post type, category and number of posts, and it returns matching posts ready to display.

Here is a simple custom query that fetches three recent posts from one category:

$recent = new WP_Query( array(
    'post_type'      => 'post',
    'category_name'  => 'news',
    'posts_per_page' => 3,
) );

if ( $recent->have_posts() ) {
    while ( $recent->have_posts() ) {
        $recent->the_post();
        the_title( '<h3>', '</h3>' );
    }
    wp_reset_postdata();
}

WP_Query supports dozens of arguments, including dates, authors, taxonomies, custom fields and ordering. The WP_Query reference lists them all.

The call to wp_reset_postdata at the end matters. It restores the global post data so the rest of the page keeps working with the main query.

For practical examples, see our guide on how to use WP_Query.

What is the Loop and how does it relate to queries?

The Loop is the code pattern that goes through the posts a query returned and shows each one; the query fetches posts, and the Loop displays them.

A classic theme template usually contains code like this:

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        the_content();
    }
}

These functions work on the main query by default. Custom queries use the same pattern but call the methods on their own object, as in the example above.

The Loop documentation explains template tags you can use inside it, such as the_title, the_excerpt and the_permalink.

What is the Query Loop block?

The Query Loop block lets you build a list of posts in the block editor without code; you choose which posts to show, and it runs a WP_Query behind the scenes.

Block themes rely on it heavily. Archive and blog templates use a Query Loop block set to inherit the main query.

Key settings in the block:

  • Inherit query from template. Uses the main query, best for archive templates.
  • Post type. Posts, pages or custom post types.
  • Filters. Categories, tags, authors and keywords.
  • Order. Newest, oldest, or alphabetical.
  • Items per page and offset.

The WordPress guide to the Query Loop block shows each option. Our explainer on the WordPress query loop covers designs and common layouts.

How do you change a query without writing a new one?

Use the pre_get_posts hook to change the main query before it runs, for example to show more posts on archives or exclude a category from the blog.

Creating a second WP_Query for something the main query already does wastes database work and breaks pagination. Changing the main query is cleaner.

add_action( 'pre_get_posts', function ( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->is_home() ) {
        $query->set( 'posts_per_page', 12 );
    }
} );

The checks matter. Without is_main_query, the change would affect every query on the page, including menus and widgets. The pre_get_posts reference has more examples.

If hooks are new to you, our explainer on what a WordPress hook is is a good starting point.

What is the difference between WP_Query, get_posts and $wpdb?

WP_Query is the full tool for post loops, get_posts is a simpler wrapper that returns an array, and $wpdb runs raw SQL for anything outside normal posts.

ToolReturnsBest for
WP_QueryA query object with loop methodsDisplaying posts with pagination
get_postsAn array of post objectsQuick lists in code, no pagination
query_postsReplaces the main queryAvoid it, as it causes bugs
$wpdbRaw database resultsCustom tables and complex reports

Avoid query_posts. It overwrites the main query in a fragile way, and the WordPress docs warn against it.

Use $wpdb only when the WordPress APIs cannot do the job. Always use its prepare method with user input to prevent SQL injection. Our guide on how to query the WordPress database covers safe raw queries.

Under the hood, all of these produce SQL SELECT statements, which the MySQL SELECT documentation describes in full.

How do queries affect WordPress performance?

Each query takes database time, so many or heavy queries slow pages; meta queries, large offsets and uncached custom queries are the usual culprits.

Things that make queries slow:

  • Complex meta queries on custom fields, which the database cannot index well.
  • Very high posts_per_page values, such as -1 on large sites.
  • Many custom queries on one page, each in a widget or block.
  • Ordering by random on big tables.

Ways to help:

  • Set no_found_rows to true when you do not need pagination.
  • Use fields => ids when you only need post IDs.
  • Cache results with transients or an object cache.
  • Use taxonomies instead of custom fields for things you filter by often.

To see which queries run on a page, install a debugging plugin. Our guide on using Query Monitor shows how to spot slow and duplicate queries. Its developer documents more on the Query Monitor website.

If a custom field query returns the wrong results, see our guide on fixing a meta query in WordPress.

Do you need to understand queries as a site owner?

Not in detail, but knowing that each page runs a query helps you understand blog settings, the Query Loop block and why some plugins slow sites down.

Site owners mostly touch queries through settings, not code. Settings > Reading controls how many posts the main query shows. The Query Loop block builds custom queries visually.

Developers need a deeper understanding. Knowing the main query, WP_Query and pre_get_posts covers most real-world needs, from custom archives to related posts sections.

Frequently asked questions

What is the main query in WordPress?

The main query is the one WordPress runs automatically for each URL. It reads the address, works out what was requested, fetches matching posts and decides which template to use. Themes display its results with the Loop or a Query Loop block set to inherit the query.

What is the difference between WP_Query and the Query Loop block?

WP_Query is the PHP class that fetches posts from the database. The Query Loop block is a visual block editor tool that builds a WP_Query for you from settings like post type, category and order. Both end up running the same kind of query.

Why should I avoid query_posts?

The query_posts function replaces the main query in a way that breaks pagination and conditional tags and adds an extra database query. Use the pre_get_posts hook to change the main query, or a separate WP_Query object for extra lists of posts.

How do I see which queries run on a WordPress page?

Install a debugging plugin such as Query Monitor. It lists every database query on the page, how long each one took, and which plugin or theme function caused it. That makes slow and duplicate queries easy to spot.

Can a query slow down my WordPress site?

Yes. Complex custom field queries, huge result sets and many separate queries on one page add database load. Simplify queries, limit results, cache output, and use taxonomies for data you filter often to keep pages fast.

Sources

  1. WP_Query class WordPress Developer Resources
  2. pre_get_posts hook WordPress Developer Resources
  3. The Loop WordPress Developer Resources
  4. Query Loop block WordPress.org
  5. SELECT statement MySQL
  6. Query Monitor Query Monitor

Is your product missing, or something out of date?

Tell us what to add or correct. We read every note and reply when we need a source. A message does not buy a ranking.

About the editors

Written and checked byWPLegible Editorial Team Independent WordPress reviews and guides

Researched from the primary sources listed above and checked against our editorial rules before publishing.