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 · Guide

How to Use WP_Query (With Examples)

How to Use WP_Query (With Examples)

Short answer

To use WP_Query, create a new WP_Query object with an array of arguments such as post_type and posts_per_page. Loop through the results with have_posts() and the_post(), then call wp_reset_postdata() so the rest of the page uses the main query post again.

Key takeaways

  • WP_Query fetches posts from the database based on an argument array you pass it.
  • Loop with have_posts() and the_post(), then call wp_reset_postdata() after the loop.
  • posts_per_page of -1 returns all posts, and offset is ignored when -1 is used.
  • tax_query filters by taxonomy with a relation of AND or OR between clauses.
  • meta_query filters by custom fields with a key, a value, and a comparison operator.
  • offset overrides paged, so never use both in one query.

What is WP_Query?

WP_Query is the WordPress class that fetches posts from the database based on the arguments you pass it.

Developer.WordPress.org states that WP_Query is the WordPress Query class, and that it provides functions for common tasks inside The Loop (checked November 2026).

You pass it an array of arguments, such as the post type and the number of posts. It returns the matching posts, and you loop through them with have_posts() and the_post().

The main query on a page is also a WP_Query object. Your own query is a second, separate query that leaves the main query alone.

Learn WordPress states that the Loop is the mechanism WordPress uses to output posts on a page, and that its functions allow you to repeat information for the default posts or for a custom query of your choice (checked November 2026).

Use WP_Query when you need a custom list of posts in a template or a plugin. A related posts block, a list of events, or a staff directory are typical uses.

A guide on how to create a custom post type in WordPress shows the post types you can query once they are registered.

What do you need before you start?

You need a WordPress site you can edit, a theme file or plugin file to hold the code, and a clear list of which posts to show.

Work on a staging copy first when the site is live. A query with no limit can return thousands of posts, so check it away from visitors.

Know the post type slug, the category or tag slug, and the number of posts you want. Those three facts shape the argument array.

Check the PHP version your site runs. WordPress.org states that WordPress recommends PHP 8.3 or greater, and that WordPress still works with PHP 7.4 and later in older setups (checked November 2026).

Know the field you will sort by, such as date, title, or a custom field value. Sorting by a custom field needs extra arguments, so decide that before you write code.

Keep the query small at first. Start with five posts and one filter, check the output, then add more filters one at a time.

How do you write a basic WP_Query?

Create a new WP_Query object with an argument array, check have_posts(), loop with the_post(), then call wp_reset_postdata().

Developer.WordPress.org states that the query is built with $the_query = new WP_Query( $args );, and that have_posts() checks whether there are posts to show (checked November 2026).

The same page states that each call to the_post() sets up the current post and the global $post variable, which template tags rely on (checked November 2026).

A basic loop looks like this:

$the_query = new WP_Query( array( 'posts_per_page' => 5 ) );

if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo esc_html( get_the_title() ) . "\n";
    }
}

wp_reset_postdata();

Resetting matters. Developer.WordPress.org states that if you use the_post() with your query, you need to run wp_reset_postdata() afterwards so template tags use the main query post again (checked November 2026).

Without the reset, later template tags on the page may show data from your custom query instead of the main post.

The arguments travel as a PHP array of key and value pairs. PHP.net states that an array in PHP is an ordered map, and that a map is a type that associates values to keys (checked November 2026).

A guide on how to create a WordPress plugin shows where query code belongs when it is part of a plugin.

Which arguments should you learn first?

Learn post_type, posts_per_page, orderby, order, cat, category_name, tag, and post_status, because they cover most lists.

post_type sets which content to fetch, such as post, page, or a custom post type slug. It accepts one slug or an array of slugs.

posts_per_page sets how many posts to show per page. Developer.WordPress.org states that 'posts_per_page' => -1 shows all posts, and that the offset parameter is ignored when -1 is used (checked November 2026).

Use -1 only on small sets. A site with thousands of posts will load them all into memory when you ask for every post at once.

orderby sets the sort field, and order sets the direction. Developer.WordPress.org lists date, title, ID, name, menu_order, rand, and comment_count among the values orderby accepts (checked November 2026).

cat takes a category ID, while category_name takes a category slug. Developer.WordPress.org states that cat uses the category ID and category_name uses the category slug (checked November 2026).

tag takes a tag slug, and tag_id takes a tag ID. A comma in the tag value means either tag, while a plus sign means all of them.

ArgumentWhat it takesExample
post_typePost type slug or array'post_type' => 'event'
posts_per_pageNumber of posts'posts_per_page' => 5
orderbySort field'orderby' => 'title'
orderASC or DESC'order' => 'ASC'
catCategory ID'cat' => 4
category_nameCategory slug'category_name' => 'news'
tagTag slug'tag' => 'cooking'
post_statusPost status'post_status' => 'publish'

How do you filter by category, tag, and taxonomy?

Filter by category and tag with the simple arguments, and switch to tax_query when you need more than one taxonomy or a logical rule.

A single category by ID is the simplest filter:

$query = new WP_Query( array( 'cat' => 4 ) );

A category by slug works the same way:

$query = new WP_Query( array( 'category_name' => 'staff' ) );

For a custom taxonomy, use tax_query. Developer.WordPress.org states that tax_query takes an array of taxonomy argument arrays, and that the relation key sets the logical link between them to AND or OR (checked November 2026).

Each inner array names the taxonomy, the field to match, and the terms:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'people',
            'field'    => 'slug',
            'terms'    => 'bob',
        ),
    ),
);
$query = new WP_Query( $args );

Developer.WordPress.org states that the field value can be term_id, name, slug, or term_taxonomy_id, and that it defaults to term_id (checked November 2026).

The operator key sets how terms match. Developer.WordPress.org states that the possible values are IN, NOT IN, AND, EXISTS, and NOT EXISTS, and that the default is IN (checked November 2026).

How do you filter by custom fields?

Filter by custom fields with meta_query, which takes an array of clauses that each name a key, a value, and a comparison.

Each clause names the key, the value, and the compare operator. The operator can be equals, not equals, greater than, greater than or equal to, less than, less than or equal to, LIKE, NOT LIKE, IN, NOT IN, BETWEEN, NOT BETWEEN, EXISTS, or NOT EXISTS.

A query for events with a price above 50 looks like this:

$args = array(
    'post_type'  => 'event',
    'meta_query' => array(
        array(
            'key'     => 'ticket_price',
            'value'   => 50,
            'compare' => '>',
            'type'    => 'NUMERIC',
        ),
    ),
);
$query = new WP_Query( $args );

Set type to NUMERIC when the value is a number. Without it, WordPress compares the values as text, and 100 would sort before 20.

You can sort by a custom field too. Set orderby to meta_value for text, or meta_value_num for numbers, and add meta_key with the field name.

Developer.WordPress.org states that meta_value and meta_value_num are among the values orderby accepts (checked November 2026).

A guide on how to optimize the WordPress database explains why queries on unindexed custom fields slow down as the post count grows.

Filter by author with the author arguments, by date with date_query, and by keyword with the s argument.

For one author, pass the author ID:

$query = new WP_Query( array( 'author' => 123 ) );

Developer.WordPress.org states that author takes the author ID, while author_name takes the user_nicename, not the display name (checked November 2026).

For several authors, pass an array of IDs with author__in. To leave authors out, use author__not_in with the same shape.

For dates, use date_query with year, month, and day keys. A query for posts from November 2026 sets year to 2026 and month to 11.

For a keyword search, pass the term as s:

$query = new WP_Query( array( 's' => 'caching' ) );

The s argument runs the same search WordPress uses on a search results page. It matches post titles and content, not custom fields, unless a plugin adds that.

Combine these filters in one argument array when you need them together. Each key you add narrows the result set further.

How do you paginate a custom query?

Paginate with the paged argument, and use max_num_pages to build the page links.

Read the current page number from the query variable, then pass it in:

$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 5,
    'paged'          => $paged,
);
$query = new WP_Query( $args );

Developer.WordPress.org states that max_num_pages holds the total number of pages, and that it is the result of $found_posts divided by $posts_per_page (checked November 2026).

Use that value to decide whether to show a next-page link. When the current page equals max_num_pages, there is no next page to link to.

Do not mix offset and paged. Developer.WordPress.org states that setting the offset parameter overrides and ignores the paged parameter, which breaks pagination (checked November 2026).

A guide on page cache vs object cache explains how caching interacts with paged lists, so page two does not show page one content.

How do you keep WP_Query fast?

Limit the result count, fetch only the fields you need, and skip the caches you do not use.

Set a small posts_per_page value. A list that shows 5 posts should ask for 5, not for every post on the site.

When you need only IDs, set fields to ids. Developer.WordPress.org states that found_posts holds the total number of posts found, and that post_count holds the number being shown, so you can check both after the query runs (checked November 2026).

Use the cache arguments when your code does not need the extra data. cache_results, update_post_meta_cache, and update_post_term_cache can each be set to false to skip that cache.

Do not run a query inside a loop over posts. That pattern runs one query per post, and a page with 20 posts will run 20 extra queries.

A guide on how to find slow plugins in WordPress shows how to spot the queries that cost the most time on a page.

What mistakes should you avoid?

Avoid forgetting wp_reset_postdata(), using query_posts(), and changing the main query from a template.

Forgetting the reset is the most common bug. Later template tags will use the last post from your custom query, so sidebars and footers show the wrong title or link.

Do not use query_posts() to change what a page shows. It replaces the main query and breaks pagination and conditional tags. Use pre_get_posts to change the main query instead.

Do not alter WP_Query properties directly. Developer.WordPress.org states that you should not alter the properties directly, and that you should use the methods instead to interact with them (checked November 2026).

Do not use posts_per_page => -1 on a large site. It loads every matching post into memory, and a site with thousands of posts can run out of memory on that page.

Do not use offset with paged, as shown above. Pick one of them, and use paged whenever the list needs page links.

A guide on how to create a custom REST API endpoint in WordPress shows how the same query arguments work when the results are served as JSON.

How do you check that a query works?

Check that the right posts appear, that the count matches, and that the rest of the page still shows the main post.

Load the page and count the results against the filters you set. Then check $query->found_posts for the total and $query->post_count for the number shown on this page.

Change one argument at a time when the result is wrong. Remove the tax_query first, then the meta_query, until the posts you expect appear.

If the page shows the wrong post after your loop, add wp_reset_postdata() right after the loop and load the page again. That fixes most cases where a sidebar or footer shows the wrong title.

If pagination shows the same posts on every page, check that paged is passed in the arguments and that offset is not set. Those two facts explain most pagination bugs.

Frequently asked questions

Should I use query_posts() to change what a page shows?

Use pre_get_posts to change the main query instead. query_posts() replaces the main query object, which breaks pagination and conditional tags. WP_Query is the right tool for a second, separate list of posts in a template or plugin.

Should I use WP_Query in the WordPress admin?

Use get_posts() instead. The WP_Query reference notes that for querying posts in the admin, get_posts() is the better choice, because wp_reset_postdata() may not behave as expected there.

Can WP_Query return every post at once?

Yes. Set posts_per_page to -1 to show all posts, but use it only on small sets. A site with thousands of posts will load them all into memory, which can exhaust the memory limit on that page.

Can I query specific posts by their IDs?

Yes. Pass post__in with an array of post IDs to limit the query to those posts, and post__not_in with an array of IDs to leave posts out. Both take arrays, not comma-separated strings.

Why does my query return no posts?

Check that the argument names are spelled right and that the values match what WordPress expects, such as a slug where a slug is needed and an ID where an ID is needed. Remove one filter at a time until the expected posts appear, then add the filters back.

How do I make a WP_Query faster?

Set fields to ids when you need only post IDs, keep posts_per_page small, and set the cache arguments to false when your code does not need the post meta or term caches. Never run a query inside a loop over posts, because that runs one extra query per post.

Sources

  1. WP_Query WordPress Developer Resources
  2. WP_Meta_Query WordPress Developer Resources
  3. WP_Tax_Query WordPress Developer Resources
  4. The Loop WordPress Developer Resources
  5. pre_get_posts WordPress Developer Resources
  6. The Loop Learn WordPress
  7. Requirements WordPress.org
  8. Arrays PHP.net

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.