Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 68 ยท The Database and the Loop

The Loop

Learn the WordPress Loop - have_posts() and the_post(), the global $post, template tags like the_title() and the_content(), setup_postdata() and a no-posts fallback.

The Loop is the piece of PHP that WordPress themes use to print posts. Before a template runs, WordPress has already asked the database for the right posts and stored them in an object. The Loop walks through that list, and for each post it makes the post's data available to template tags such as the_title() and the_content().

If you understand the Loop, you understand how almost every classic theme file works. Archives, search results, the blog index and single posts all use the same few lines. This lesson shows what those lines do, what the global $post variable is, and how to handle the case where nothing matches. It builds on the database schema, because the loop prints rows of the wp_posts table.

The real Loop only runs inside WordPress, so the real code below is read-only. The runnable examples use a small stand-in written in plain PHP. It copies the shape of have_posts() and the_post(), not WordPress's actual implementation.

The standard Loop

This is the Loop as it appears in a typical index.php. It is real WordPress code:

PHP
<?php if ( have_posts() ) : ?>

    <?php while ( have_posts() ) : the_post(); ?>

        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <h2>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            </h2>
            <div class="entry">
                <?php the_excerpt(); ?>
            </div>
        </article>

    <?php endwhile; ?>

<?php else : ?>

    <p>Nothing found.</p>

<?php endif; ?>

Read it in three parts:

  1. have_posts() answers one question: is there another post left to show? It returns true or false.
  2. the_post() moves to the next post and sets up the global state for it. After the call, template tags know which post you mean.
  3. The else branch runs when the query matched nothing at all.

The posts come from the main query, which WordPress builds from the URL before your template loads. You never call the database yourself in the standard Loop. The main query lesson explains how it is built and how to change it.

flowchart TD
    A["Request: /blog/"] --> B["WP_Query fetches posts"]
    B --> C{"have_posts()?"}
    C -- "no" --> D["Print the no-posts message"]
    C -- "yes" --> E["the_post(): set global $post"]
    E --> F["Template tags print the post"]
    F --> C

The Loop repeats the same template code for each post until have_posts() returns false.

What the_post() does

have_posts() and the_post() are thin wrappers. They call methods on the global $wp_query object, which is an instance of WP_Query. In plain terms:

  • have_posts() checks whether the query's internal counter has reached the end of its list.
  • the_post() advances the counter, copies the current post into the global $post, and calls setup_postdata().

setup_postdata() fills a handful of related globals, such as $authordata, $pages and $page, and prepares the content for pagination with the <!--nextpage--> tag. This is why the_content() knows which page of a multi-page post to show.

You rarely touch these details, but they explain a common bug. Template tags read the global $post. If you loop over posts yourself, the tags print whatever post is currently global, not your post:

PHP
<?php
// Wrong: the template tags still refer to the page's own post.
$ids = get_posts( [ 'post_type' => 'book', 'fields' => 'ids' ] );
foreach ( $ids as $id ) {
    the_title(); // prints the title of the CURRENT page, not $id
}

The fix is to use get_the_title( $id ), which takes an explicit ID, or to set up the post data yourself.

Template tags in the Loop

Template tags come in two forms. Names that start with the_ echo their result. Names that start with get_the_ return a value so you can store or change it first. Most functions that work with the current post have both.

Echoes Returns What it gives you
the_title() get_the_title() The post title, with filters applied
the_content() get_the_content() The full content, with blocks and shortcodes processed
the_excerpt() get_the_excerpt() The manual excerpt or an automatic short version
the_permalink() get_permalink() The post's URL
the_ID() get_the_ID() The numeric ID
the_author() get_the_author() The author's display name
the_date() get_the_date() The publish date, formatted

Two details matter in practice:

  • The the_* versions already run the value through filters. the_title() applies the the_title filter, and the_content() applies the_content, which is where blocks and shortcodes turn into HTML. Calling the_content() is not the same as echoing the raw post_content column.
  • the_title() accepts text to print before and after. It prints nothing for an empty title, so the extra text disappears with it: the_title( '<h1>', '</h1>' );.

You should still escape values you print yourself. the_title() is safe to echo directly, but when you use get_the_title() inside an attribute, wrap it with esc_attr(). See escaping output.

A mini Loop you can run

WordPress cannot run on this site, so here is a stand-in. The MiniQuery class keeps a list of post arrays and a position. have_posts() and the_post() work on a global query object, just like the real ones. Run it and watch how $post changes.

PHP A mini Loop with have_posts and the_post

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows one <article> per post. Notice that the template code never mentions a post number. The only thing that changes between iterations is the global $post, which the_post() replaces each time.

Handling no results

A query can match zero posts: an empty category, a search for a word nobody used, or a page number beyond the last page. Always give visitors something useful in that case. The else branch is the place for it, and real themes often move it into a template part such as content-none.php.

PHP The no-posts fallback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second search returns an empty list, so render_loop() prints the friendly message instead of an empty <ul>. This is exactly what the else branch of the real Loop is for.

Using setup_postdata() with your own list

Sometimes you hold an array of post objects and want to use template tags on them, for example after calling get_posts(). You can do that by assigning each object to the global $post and calling setup_postdata():

PHP
<?php
global $post;

$books = get_posts( [ 'post_type' => 'book', 'numberposts' => 5 ] );

foreach ( $books as $post ) {
    setup_postdata( $post );
    ?>
    <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
    <?php
}

wp_reset_postdata();

The foreach uses the global name $post as its loop variable on purpose. After the loop, wp_reset_postdata() restores the global to the post the page was originally showing. Forgetting this call is a classic source of strange behavior in the footer or sidebar, where tags suddenly print the last book instead of the page. WP_Query in depth shows the reset in a custom-query context, where it matters most.

Common mistakes

  • Calling template tags outside the Loop. Tags such as the_title() rely on $post. Outside the Loop they print the first post, the page's own post, or nothing. Use the get_* versions with an explicit ID when you are not in a Loop.
  • Running the Loop twice without a rewind. After the Loop ends, have_posts() is false. Call rewind_posts() if you need to loop over the same main query a second time.
  • Printing before checking. Without the if ( have_posts() ) wrapper you cannot show a fallback, and you may print empty wrapper markup.
  • Modifying $post and forgetting to restore it. Always pair custom loops with wp_reset_postdata().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does have_posts() return?

    have_posts() is a yes-or-no check on whether the query's counter has reached the end of its list.
  2. 2. What is the main job of the_post() inside the Loop?

    the_post() moves the query to the next post, copies it into the global $post and calls setup_postdata() so template tags know which post to use.
  3. 3. What is the difference between the_title() and get_the_title()?

    The the_ functions print, the get_the_ functions return a value so you can store or modify it first.
  4. 4. You loop over posts from get_posts() with your own foreach, using setup_postdata(). What should you call afterwards?

    wp_reset_postdata() restores the global $post to the page's own post so later template code is not affected.

Summary

  • The Loop prints the posts that the main query has already fetched: have_posts() asks, the_post() advances.
  • the_post() sets the global $post and calls setup_postdata(). Template tags read that global.
  • the_* tags echo, get_the_* tags return; the the_* versions apply filters such as the_content.
  • Always handle the no-posts case in the else branch.
  • If you assign $post and call setup_postdata() yourself, finish with wp_reset_postdata().
  • The runnable examples here are plain-PHP stand-ins; the real Loop code runs only inside WordPress.

Next: WP_Query in Depth