October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How the WordPress Loop Works and How to Customize It

Understand the WordPress Loop, distinguish the main query from secondary queries, customize archives with pre_get_posts, and reset post data safely.
Length12 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The WordPress Loop is the code that turns a query’s results into the posts, pages, or custom post types visitors see. The main query is built for the current URL, and a theme’s template consumes it one post at a time with have_posts() and the_post(). To change that main result set, modify the query before it runs with pre_get_posts; to display an additional list, create a separate WP_Query or get_posts() query and restore the original post context afterward.

Understanding which query you are changing, when it runs, and whether it changes global post state prevents the most common Loop bugs: missing pagination, incorrect titles or links, duplicated posts, and template tags showing data from the wrong post.

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.

What the WordPress Loop does

WordPress builds a query from the requested front-end URL. A home page, category archive, search results page, author archive, date archive, or singular post request each produces a main query with its own query variables and result set. The selected template then uses the Loop to read those results and render markup.

The WordPress Theme Handbook describes the Loop as “the default mechanism WordPress uses for outputting posts through a theme’s template files.” In practical terms, the Loop is an iteration over the posts returned by the current query. It does not decide which posts should exist by itself; it reads the query that has already been prepared and exposes one result at a time to template tags.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

A minimal Loop has four parts:

  1. Check whether another result is available with have_posts().
  2. Advance to that result with the_post().
  3. Output fields such as the title, content, author, date, and permalink.
  4. Provide an empty-state branch when no result exists.

The same pattern works with the global main query and with a secondary WP_Query object. The method names look similar, but the object on which they are called determines which result set is being consumed.

The basic Loop, line by line

<?php
if ( have_posts() ) :
    while ( have_posts() ) :
        the_post();
        the_title();
        the_content();
    endwhile;
else :
    echo 'No posts found.';
endif;
?>

have_posts() checks availability

On the main query, have_posts() checks whether another post is available for the Loop. It returns a Boolean value. A true result allows the loop body to run; a false result sends execution to the else branch or ends the while loop.

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.

It is a stateful check, not a database query you should treat as a harmless look-ahead. When the query reaches the end of its results, WP_Query::have_posts() returns false, fires the loop_end action, and rewinds the posts. That rewind means a later check can start from the beginning again. Calling have_posts() unexpectedly inside a loop can therefore alter the point at which you think iteration is occurring.

the_post() advances and sets context

the_post() advances the query’s internal pointer to the next result and sets up the current post. Template tags such as the_title(), the_content(), the_author(), the_permalink(), and date or taxonomy tags then read the post that the_post() selected.

The function also updates the global post context used by many template functions. That is why a secondary Loop can make code after it display the secondary post’s title or link unless you restore the original context.

The loop body runs once per returned post

Everything between the_post() and endwhile runs for each result. Put the complete card or article structure there, including the heading, link, metadata, excerpt, thumbnail, and content you want repeated. Put page-level wrappers outside the Loop so they are not emitted once per post.

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.

The empty branch is part of a complete Loop

A query can legitimately return zero posts. Search terms, empty archives, unpublished content, restrictive taxonomies, and custom filters all create this situation. Keep an explicit empty-state branch and give it useful output, such as a heading explaining that no matching posts were found and a search form or navigation back to a broader archive.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

How the main query reaches the template

For a front-end request, WordPress parses the URL into query variables, constructs the main WP_Query, and chooses a template through the theme’s template hierarchy. The chosen template’s primary Loop consumes that main query. Archive templates commonly list many posts; a singular template normally receives one post; search templates receive the results matching the search request.

The important distinction is that the main query represents the page the visitor requested. Its variables include information such as the post type, taxonomy, search term, date, author, page number, and posts-per-page setting. Replacing that query inside a template can discard information that WordPress derived from the URL, which is why the method used to customize it matters.

In a normal theme, do not instantiate a new query merely to replace the archive’s existing results. Adjust the existing main query before it executes, or leave it alone and create a separate query for an additional component such as a “related posts” block.

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

Customize the main query with pre_get_posts

Use the pre_get_posts action when the goal is to change which posts the requested page displays. The hook runs after WordPress has created the query variables but before the database query runs, so changing a parameter there affects the SQL that retrieves the main results.

<?php
function my_archive_size( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->is_archive() ) {
        $query->set( 'posts_per_page', 15 );
    }
}
add_action( 'pre_get_posts', 'my_archive_size' );
?>

Why each condition matters

  • ! is_admin() limits the change to front-end requests. Without it, an archive setting intended for visitors could also affect administration screens.
  • $query->is_main_query() prevents the callback from changing every query that happens to run during the request. Sidebars, footers, widgets, REST requests, and plugins can all create additional queries.
  • $query->is_archive() narrows the change to archive requests. Replace it with the appropriate conditional method when your rule applies only to a search, a specific post type archive, or another request type.
  • $query->set( 'posts_per_page', 15 ) changes a query variable before retrieval. The number is an example setting; choose the value that fits your design and pagination plan.

Use conditional methods on the passed $query object rather than assuming the global query is the one being filtered. The callback may run for several queries during one request, and broad changes can produce failures far from the template where the code was written.

Changing archive filters safely

You can set other query variables in the same way when the requirement is to change the main archive’s result set. Typical examples include restricting a post type archive, adding a taxonomy constraint, changing ordering, or changing the number of posts per page. Keep the rule specific to the intended request and test the first page and later pages.

Pagination is part of the main query’s behavior. If you change the result count or filters before SQL runs, WordPress can calculate the number of pages from the modified query. Avoid designs that use an arbitrary offset unless you also account for how that offset changes page counts and which posts appear on every page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Create an additional Loop with WP_Query

Use a secondary query when the page should keep its main results and also show another set of posts. A related-content panel, a news feed in a game article, or a list of posts from a particular category are separate-content use cases.

<?php
$related = new WP_Query( [
    'posts_per_page' => 5,
    'category_name'  => 'news',
] );

if ( $related->have_posts() ) :
    while ( $related->have_posts() ) :
        $related->the_post();
        the_title( '<h2>', '</h2>' );
    endwhile;
else :
    echo 'No related posts found.';
endif;

wp_reset_postdata();
?>

Call methods on the query object

A secondary query has its own result set, so call $related->have_posts() and $related->the_post(). Calling the unqualified global functions in a custom-loop example can accidentally operate on the main query instead of the object you intended to display.

Reset global post data after the loop

Calling $related->the_post() changes the global post context used by template tags. Run wp_reset_postdata() immediately after the secondary Loop, before rendering code that depends on the main query’s current post. The reset restores the global context while leaving the secondary query object available if you need to inspect it further.

Resetting is required even when the secondary Loop appears to work in a simple template. A later breadcrumb, navigation link, comment section, structured-data routine, or template part may read the global post and silently output fields from the last related post unless the context is restored.

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

Handle an empty secondary query

Secondary queries can return zero results for the same reasons as the main query. Include an empty branch or deliberately suppress the entire component when there is nothing to show. Reset post data outside the branch so the main context is restored whether or not the query produced posts.

Use get_posts() for a simple additional list

get_posts( $args ) is another way to retrieve posts for an additional component. It returns posts from a separate query and does not alter the main Loop. This can be convenient when you want an array to process with foreach rather than a full query object.

<?php
$items = get_posts( [
    'posts_per_page' => 5,
    'category_name'  => 'news',
] );

if ( $items ) :
    echo '<ul>';
    foreach ( $items as $item ) :
        echo '<li>';
        echo esc_html( get_the_title( $item ) );
        echo '</li>';
    endforeach;
    echo '</ul>';
else :
    echo 'No related posts found.';
endif;
?>

Because this pattern returns an array and does not run the_post() for each item, it does not take over the global post context in the same way as a secondary Loop. If you deliberately set up global post data while processing the array, apply the appropriate reset before returning to main-query output.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Why query_posts() should be avoided

The official developer reference warns that query_posts() “will completely override the main query” and is not intended for use by plugins or themes. It is an anti-pattern for most customization work because it replaces the query WordPress built for the URL instead of modifying that query before execution.

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

What can go wrong

  • URL-derived query variables can be discarded, so an archive, search, or taxonomy request no longer behaves like the page the visitor requested.
  • Pagination can become incorrect because the original query’s page and found-post counts are no longer represented consistently.
  • Other code that expects the main query can receive a different result set, producing confusing template and plugin interactions.
  • The database may be queried again after WordPress has already prepared the main request, adding work without solving a problem that pre_get_posts or a secondary query handles more cleanly.

If you need to change the requested page, use a narrowly targeted pre_get_posts callback. If you need an extra list, instantiate WP_Query or use get_posts(). These choices make the scope of the change explicit.

Choosing the right customization method

Goal Recommended method When it runs Main-query state Reset needed
Change which posts an archive or search page returns pre_get_posts on the targeted main query After query variables are created, before SQL runs Changes the main query by design No separate post-data reset; preserve pagination and request conditions
Show a related or featured list alongside the requested page new WP_Query( $args ) Where the template executes the additional component Secondary query changes global post context while its Loop runs Yes: call wp_reset_postdata() after the_post()
Retrieve a simple array for an additional list get_posts( $args ) Where the function is called Does not alter the main Loop by itself Not for the basic array pattern; reset if you manually set global post data
Replace the requested page’s query from inside a template Do not use query_posts(); move the rule to pre_get_posts Not recommended Overrides the main query and can break URL variables and pagination Not a safe customization strategy
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Build a customized Loop step by step

Recipe: change an archive’s page size

  1. Identify the request type that should change, such as a front-end archive.
  2. Add a pre_get_posts callback in the appropriate theme or plugin code.
  3. Guard the callback with ! is_admin(), $query->is_main_query(), and the most specific conditional method available.
  4. Set posts_per_page or another needed query variable before the query runs.
  5. Visit the archive’s first page and at least one later page. Confirm that the item count, next/previous links, and page boundaries agree.
  6. Check that unrelated queries, such as sidebar lists and administration screens, still use their own settings.

Recipe: add a related-posts component

  1. Define the secondary query arguments, including the number of posts and the category, taxonomy, post type, or ordering rule.
  2. Instantiate WP_Query with those arguments.
  3. Check the object with $query->have_posts().
  4. Inside the while loop, call $query->the_post() before using template tags.
  5. Render the complete repeated card or heading structure.
  6. Provide an empty branch or suppress the component when no posts match.
  7. Call wp_reset_postdata() before any markup that should use the main query’s current post.

Recipe: inspect a Loop without disturbing it

Keep diagnostic checks outside the iteration unless you understand the query state they change. An extra have_posts() call at the end can rewind the query after it reports false. If you need to count, paginate, or inspect results, use the query’s documented properties and methods rather than probing the Loop with repeated availability checks.

Common Loop failures and fixes

Every card shows the same post

Make sure the_post() is inside the while loop and is called on the intended query object. If the call is missing or occurs outside the loop, template tags continue reading the same global post.

A related list changes the article title below it

The secondary Loop changed global post context. Add wp_reset_postdata() immediately after the loop and before rendering the rest of the main template.

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

The archive ignores the custom post count

Check that the pre_get_posts callback is running on the front end, tests $query->is_main_query(), and uses the correct conditional method. A callback that targets every query may also be changing a different query, while a callback that checks the wrong request type will never match.

Pagination skips posts or shows the wrong number of pages

Do not replace the main query with query_posts(). Apply filters before SQL with pre_get_posts, avoid an unplanned offset, and test several page numbers after changing the result set.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

The page is blank when there are no matches

Add an explicit else branch for every query that can be empty. A no-results message, search form, or link to a broader archive gives the visitor a usable outcome instead of an empty container.

A custom Loop appears to affect a sidebar or footer

Review where the global post context is changed and whether it is reset. Also verify that a pre_get_posts callback is limited to the intended main query; broad callbacks can alter unrelated loops during the same request.

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

State, timing, and pagination: the three decisions behind every customization

Target

First decide whether you are changing the page requested by the visitor or adding another component. Main-query changes belong in pre_get_posts; additional content belongs in a secondary query or get_posts().

Timing

If the result set must be different before database retrieval, change query variables in pre_get_posts. If the page already has its main results and you are retrieving another list while rendering the template, use WP_Query or get_posts().

State impact

Ask whether your code changes global $post. A secondary WP_Query Loop that calls the_post() does; restore it with wp_reset_postdata(). A simple get_posts() array does not alter the main Loop by itself.

Keeping these decisions explicit makes Loop code easier to maintain: the main query remains the authoritative representation of the requested URL, secondary queries are isolated, and every change to global state has a visible cleanup step.

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

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.

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair 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.