October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk11 min

How to Use WP_Query in WordPress With Examples

A complete WP_Query guide covering custom loops, arguments, taxonomy filters, pagination, global post cleanup, status permissions and performance controls.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

WP_Query lets a WordPress template request a specific set of posts, pages, or custom post types and then render them with the normal Loop. Build an arguments array, pass it to new WP_Query(), iterate with have_posts() and the_post(), and call wp_reset_postdata() when the secondary loop ends. The examples below cover filtering, sorting, taxonomy queries, pagination, security, and performance-related options.

What WP_Query does

WP_Query is a WordPress class that accepts query arguments and returns posts matching those conditions. You can select a post type, limit the number of results, sort them, search text, filter by author or taxonomy, select particular IDs or slugs, and choose which data is returned.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A query created with new WP_Query() is normally a secondary query. It runs in addition to the page request’s main query, so it is suitable for a related-posts block, a featured-content panel, an archive component, or a custom listing inside a template. The query object exposes the matching posts and metadata such as max_num_pages for pagination.

Your first custom loop

The standard pattern is to define arguments, instantiate the class, test for results, loop through them, and restore the original post context.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
<?php
$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 5,
    'orderby'        => 'date',
    'order'          => 'DESC',
);

$custom_query = new WP_Query( $args );

if ( $custom_query->have_posts() ) {
    while ( $custom_query->have_posts() ) {
        $custom_query->the_post();
        ?>
        <article>
            <h2><?php the_title(); ?></h2>
            <div><?php the_excerpt(); ?></div>
        </article>
        <?php
    }
} else {
    echo '<p>No matching posts found.</p>';
}

wp_reset_postdata();

have_posts() checks whether another result is available. the_post() advances the query and sets the global post used by template tags such as the_title(), the_excerpt(), the_permalink(), and the_content(). The final wp_reset_postdata() is not optional when the loop has called the_post(): it restores the main query’s current post so template tags that follow continue to refer to the page being displayed.

Choose arguments deliberately

Arguments determine both which records are returned and how the template should handle them. Set the values that matter to the feature instead of relying on implicit ordering or content-type assumptions.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Argument What it controls Example
post_type The content type to query. The documented default is posts; pages and custom post types must be requested explicitly. 'post_type' => 'page' or 'post_type' => 'book'
posts_per_page How many results are returned for a page of results. A value of -1 requests all matching posts. 'posts_per_page' => 10
paged The results page used for ordinary pagination. 'paged' => $paged
page The page query variable that can be needed by a static front-page template. 'page' => $page
orderby and order The sort field and direction. Choose them explicitly when display order matters. 'orderby' => 'date', 'order' => 'DESC'
author Restricts results to an author. 'author' => 42
s Searches post content using a search term. 's' => 'accessibility'
post__in and slug filters Limits results to selected IDs or slugs. 'post__in' => array( 12, 19 )
post_status Restricts the status of returned posts. 'post_status' => 'publish'
tax_query Applies one or more taxonomy conditions using taxonomy, field, and terms. 'tax_query' => array( array( 'taxonomy' => 'topic', 'field' => 'slug', 'terms' => array( 'guides' ) ) )
fields Chooses whether the result contains full post objects, IDs, or ID-to-parent data. 'fields' => 'ids'
cache_results, update_post_meta_cache, and update_post_term_cache Controls documented post, metadata, and term-cache population. 'fields' => 'ids' with cache settings chosen for the actual loop

Target a post type

Use post_type whenever the template expects a particular content model. If you omit it, the documented default is posts; pages are not silently included. A registered custom post type is identified by its slug.

<?php
$args = array(
    'post_type'      => 'event',
    'posts_per_page' => 8,
    'orderby'        => 'date',
    'order'          => 'DESC',
);
$events = new WP_Query( $args );

An array can request more than one type when the component is intentionally mixed:

<?php
$args = array(
    'post_type'      => array( 'post', 'page' ),
    'posts_per_page' => 6,
);
$mixed_content = new WP_Query( $args );

Keep the content types explicit so a later post-type registration or template change cannot unexpectedly alter the component.

Filter by taxonomy, author, search, IDs, or slugs

Taxonomy conditions

Use tax_query for category-like or custom taxonomy requirements. Each condition supplies a taxonomy, the field used to identify terms, and the terms to match.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
<?php
$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 10,
    'tax_query'      => array(
        array(
            'taxonomy' => 'topic',
            'field'    => 'slug',
            'terms'    => array( 'wordpress', 'themes' ),
        ),
    ),
);
$topic_posts = new WP_Query( $args );

Use the term field that matches the values you possess. A slug-based condition expects slugs; an ID-based condition should supply IDs. Multiple taxonomy clauses can be added when the result must satisfy more than one taxonomy requirement.

Author and keyword filters

Author and search arguments can be combined with the other constraints:

<?php
$args = array(
    'post_type'      => 'post',
    'author'         => 42,
    's'              => 'block editor',
    'posts_per_page' => 5,
);
$author_matches = new WP_Query( $args );

The s value is a WordPress search term, not a PHP regular expression. If the search box is user supplied, pass the value through the normal input-validation and output-escaping practices used by the rest of the site.

Selected IDs or slugs

Use an inclusion list when an editor or another query has already chosen the records to display:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
$args = array(
    'post_type'      => 'post',
    'post__in'       => array( 117, 204, 319 ),
    'posts_per_page' => 3,
);
$chosen_posts = new WP_Query( $args );

When a specific sequence is important, define an explicit ordering strategy rather than assuming the database will preserve the order of the ID list. The orderby and order arguments are the documented controls for display order.

Control count and ordering

posts_per_page controls how many matching posts are returned for each results page. Use a positive number for a bounded component. A value of -1 requests all matching posts, which is appropriate only when the template genuinely needs the complete set.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Always set orderby and order when readers depend on a predictable sequence. For example, newest-first content can use 'orderby' => 'date' and 'order' => 'DESC'. A query that does not state an order leaves the component dependent on the query’s default ordering rather than communicating the intended editorial rule.

Paginate a custom query

Read the current page, pass it as paged, and give paginate_links() the custom object’s max_num_pages. The latter is calculated from the query’s result count and is the correct total for that secondary result set.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
$paged = max( 1, (int) get_query_var( 'paged' ) );

$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 5,
    'paged'          => $paged,
);

$custom_query = new WP_Query( $args );

if ( $custom_query->have_posts() ) {
    while ( $custom_query->have_posts() ) {
        $custom_query->the_post();
        the_title( '<h2>', '</h2>' );
    }

    echo paginate_links( array(
        'total' => $custom_query->max_num_pages,
    ) );
}

wp_reset_postdata();

On a static front-page template, the WordPress reference notes that the page query variable may be the one needed for the current page value. Check which query variable your template receives before wiring the links.

Why offset breaks ordinary pagination

Do not combine a fixed offset with ordinary paged pagination. The offset parameter overrides or ignores paged, so every page can skip the wrong records or repeat results. If the design must skip an initial group, calculate a page-aware offset yourself and test the first, middle, and final pages; otherwise, remove offset and rely on paged.

Understand the global post context

Calling the_post() on a secondary query changes the global post context used by template tags. This is why a related-posts loop can otherwise cause the surrounding template to print the related post’s title, URL, or metadata.

After the loop, call:

<?php
wp_reset_postdata();

The WordPress Developer Resources class reference states: ‘If you use the_post() with your query, you need to run wp_reset_postdata() afterwards to have template tags use the main query’s current post again.’

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

wp_reset_postdata() versus wp_reset_query()

A new WP_Query object is a separate query and requires post-data restoration after its loop. It does not call for wp_reset_query(). The separate wp_reset_query() function is associated with restoring the main query after code has used query_posts(), which is a different mechanism. Do not substitute one reset function for the other simply because both names contain the word reset.

Main query or secondary query?

The request’s main query determines the page WordPress is serving, such as a category archive, a search page, or a singular post. A secondary query created with new WP_Query() adds another result set inside that page.

Use a secondary query when the page needs an additional component with its own post type, filters, count, or ordering. If the requirement is to change the archive that WordPress is already preparing, adjust the main query through the appropriate query-filtering mechanism instead of creating a second loop and hiding the first one. Creating an extra query does not automatically replace the main query.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Post statuses and access control

Public listings normally query published content. If you explicitly request non-public statuses, treat that as an authorization-sensitive operation. A user-contributed note on the official class reference warns that explicit status selection can bypass capability-filtering logic and points to the perm argument, with values such as readable or editable, when access restrictions are required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Because that warning is user-contributed rather than a normative guarantee for every WordPress version, validate the behavior against the site’s version, roles, and privacy requirements. Do not assume that naming a private or draft status alone makes a front-end query safe.

<?php
$args = array(
    'post_type'   => 'post',
    'post_status' => 'private',
    'perm'        => 'readable',
);
$private_query = new WP_Query( $args );

Only expose non-public records when the current user is authorized to see them, and escape any rendered values in the same way as other template output.

Choose the returned data

By default, a query supplies post objects suitable for normal template tags. The fields argument can request IDs or ID-to-parent data instead. Returning IDs is useful when the next operation only needs identifiers, such as passing them to another lookup or building a lightweight list.

<?php
$id_query = new WP_Query( array(
    'post_type'      => 'post',
    'posts_per_page' => 20,
    'fields'         => 'ids',
) );

foreach ( $id_query->posts as $post_id ) {
    echo '<li>' . esc_html( (string) $post_id ) . '</li>';
}

If the template needs titles, excerpts, links, metadata, or taxonomy terms, request the normal post objects and use the loop. Selecting IDs does not provide the post object that those template tags expect.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cache controls and performance decisions

The class reference documents cache_results, update_post_meta_cache, and update_post_term_cache as controls for populating post, metadata, and term caches. Cache population is generally appropriate. Disabling one of these caches is a situational choice for a loop that deliberately uses only a subset of the available data.

For example, a component that returns IDs and never reads metadata or terms may have a reason to review those settings, while a card grid that prints custom fields and taxonomy labels generally benefits from the corresponding cache data being available. Measure the actual template’s needs before changing cache behavior; a shorter argument list is not automatically faster.

Handle an empty result set

Always provide a branch for no matches. It prevents an empty container from appearing and gives visitors a useful explanation.

<?php
if ( $custom_query->have_posts() ) {
    while ( $custom_query->have_posts() ) {
        $custom_query->the_post();
        ?>
        <article>
            <h2><a href='<?php the_permalink(); ?>'><?php the_title(); ?></a></h2>
        </article>
        <?php
    }
} else {
    echo '<p>Sorry, no posts matched your criteria.</p>';
}
wp_reset_postdata();

Keep the no-results message specific when the component has a meaningful filter, such as a selected topic or author. The query itself still needs resetting after either branch when the loop may have advanced the post context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A complete filtered, paginated example

This template fragment combines a custom post type, a taxonomy condition, explicit ordering, pagination, and cleanup.

<?php
$paged = max( 1, (int) get_query_var( 'paged' ) );

$args = array(
    'post_type'      => 'event',
    'posts_per_page' => 6,
    'paged'          => $paged,
    'orderby'        => 'date',
    'order'          => 'DESC',
    'tax_query'      => array(
        array(
            'taxonomy' => 'event_type',
            'field'    => 'slug',
            'terms'    => array( 'webinar' ),
        ),
    ),
);

$events = new WP_Query( $args );

if ( $events->have_posts() ) {
    while ( $events->have_posts() ) {
        $events->the_post();
        ?>
        <article class='event-card'>
            <h2><a href='<?php the_permalink(); ?>'><?php the_title(); ?></a></h2>
            <div class='event-card__excerpt'><?php the_excerpt(); ?></div>
        </article>
        <?php
    }

    echo paginate_links( array(
        'total' => $events->max_num_pages,
    ) );
} else {
    echo '<p>Sorry, no posts matched your criteria.</p>';
}

wp_reset_postdata();

The taxonomy slug, post type, and term in this sample are illustrative values; replace them with the names registered by your site. The structural rules remain the same: use the query object for the loop and its page count, then restore post data.

Debugging checklist

  • No results: verify post_type, taxonomy name, term field, term values, author ID, search text, and status. Remember that the default content type is posts, not pages.
  • Wrong order: set both orderby and order instead of relying on an implicit sequence.
  • Pagination repeats or skips: remove a fixed offset or replace it with explicit page-aware offset logic. Confirm that paged is an integer of at least 1.
  • Pagination shows the wrong number of pages: pass the custom object’s max_num_pages to paginate_links(), not the main query’s total.
  • Surrounding template tags show a related post: call wp_reset_postdata() immediately after the secondary loop.
  • Private content leaks: review explicit post_status values, the perm setting, the current user’s capabilities, and the site’s WordPress version before displaying non-public records.
  • Template tags fail after using fields => 'ids': switch back to full post objects when the template needs titles, excerpts, links, metadata, or terms.
  • Static front-page pagination does not advance: check whether the template needs the page query variable rather than paged.

Practical rules to keep

  1. Declare the post type and result count that the component actually needs.
  2. Set ordering explicitly whenever users rely on chronology or editorial sequence.
  3. Use tax_query, author, search, ID, slug, and status arguments instead of filtering a larger result set in PHP.
  4. Use paged with paginate_links() and the query object’s max_num_pages for custom pagination.
  5. Do not pair ordinary paged pagination with offset unless you calculate the offset for every page.
  6. Call wp_reset_postdata() after every secondary loop that uses the_post().
  7. Choose fields and cache controls according to the data the template reads, not as blanket optimizations.
  8. Validate authorization whenever a query requests anything other than publicly readable content.

Conclusion

A reliable WP_Query implementation is a small, explicit contract: arguments define the result set, the query object drives the Loop, pagination uses that object’s page count, and post data is reset before the surrounding template continues. Once those boundaries are in place, the same pattern scales from a five-post sidebar to filtered custom-post-type archives without taking over WordPress’s main query.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.