A Beginners Guide to the Loop in WordPress


While discussing WordPress, specific themes, and plugin development, the loop is inevitably the most important concept. The loop is the heart of WordPress themes development, and when you are looking at any blog like tutorialspanel.com’s home page, you see the content fetched and displayed by the loop.

An introduction to the Loop in WordPress

In WordPress, the loop determines what content to display on a web page. The loop can display a single piece of content, or it can show a group of posts that fall under the same category. WordPress uses the loop as the by default mechanism to access posts or pages.

Through loop, it is straightforward to customize what content you want to display and where. The loop at its core is just a loop just like in any other programming language. It iterates through the content, accesses your posts or pages one by one and displaying till the loop has no more content to display.

You can customize the loop to display only specific posts or pages that fulfill certain requirements. You can easily change the loop to display posts from a particular category or exclude content from one particular author.

WordPress has some essential functions that are primitive only to the loop. The template tags are explicitly used inside the loop. For example, the_category() displays the category of the current post.

The loop

Let’s take a look at the minimal code that makes the loop.

<?php
if (have_posts()) {
    while (have_posts()) {
        the_post();
        the_content();
    }
}
?>

That’s it.

With these few lines of code, you can fetch and display every post saved in the wp_posts table.
The loop starts with a function have_posts(). This function returns true if there are any post(s) to display, or false otherwise.

If WordPress gets true, the next statement is a while loop that uses a function have_posts() to determine if there any post left to display, if yes(return true), the_post() function will display the post. With post here, we mean the content of the post and not the title or metadata of the post.

To display every post with title and author name, you have to modify the loop’s inner body.

<?php
if (have_posts()) {
    while (have_posts()) {
        the_post();
        the_title();
        the_content();
        the_author();
    }
}
?>

The function the_post() takes the current post from the available posts and make it available for the loop to use. Without the_post(), many templates tags won’t work inside the loop or web page will suffer the infinite loop.

You can add an image in the loop as well using the_post_thumbnail() function.

<?php
if (have_posts()) {
    while (have_posts()) {
        the_post();
        echo "<h2>";
        the_title();
        echo "</h2>";
        the_post_thumbnail();
        the_excerpt();
    }
} else {
    echo "Soryy, there is nothing to display";
}
?>

The number of posts displayed on a web page depends on the default number of posts to display (Go to Settings > Reading > Reading Settings > Blog pages show at most (The default value is 10) posts.

Either you want to display only one post or a list of posts, interestingly, it doesn’t impact on the loop. The above loop has the_post_thumbnail() function which displays the thumbnail image(if any) of the post. The other function the_excerpt() will show the excerpt of the post instead of the entire post.

Template Tags

Like thumbnail and excerpt, there are few other elements which loop can display, such as the author, publishing date, title, etc. Below you can see a list of such functions along with a little explanation.

  • the_content() will display the content of the post. If the post has a quick tag <!—more ..> to mark the “cut-off” point for the post, the function will only display the content up to <!—more– > point with a non-permalink to a web page having a single post. This tag will not function in single.php and will be ignored.
  • the_excerpt() display the first 55 words of the post’s content then add a […] or ‘read more’ link that refers to single.php with current’s post full content.
  • the_author() displays the author name of the current post or page. This can be written as </p> This tutorial was written by <?php the_author(); ?></p>
  • the_ID() displays the numeric ID of the current post or page. For example Article Number: <?php the_ID(); ?>
  • the_meta() function is used to display custom fields known as post meta. Custom fields are arbitrary extra information attached to any post. This could include information such as:
Reading Time: 15 min
Tutorial level: Advanced
Pre-requisite courses: HTML, PHP, MySQL

Meta-data is always in key/value pairs.

To enable custom fields, click on the Screen Options at the top-right corner of Admin’s dashboard. Check the Custom Fields options from the drop-down menu, and you will see the custom field at the end of the post editor.

Like thumbnail and excerpt, there are few other elements which loop can display, such as the author, publishing date, title, etc. Below you can see a list of such functions along with a short description.

WordPress Screen Options
WordPress Custom Fields

Enter the name of the meta-data, value, and click on ‘Add Custom Field”.

WordPress add/update Custom Fields

To display this meta-data use the_meta(“Reading Time”); within loop.

  • the_tags() displays the tag(s) associated with the current post.
  • The_title() display the title of the current post or page. You can style it using CSS. For example:
    echo “<h2>”; the_title(); echo “</h2>”;
    h2{color:cyan;} changes the color of the title of the post to cyan.
  • Next_post_link() displays a link to the next post( a post published after the current post) and preveious_post_link() displays a link to the previous post (a post published before the current post).
  • the_category() displays a link to the category or categories of the current post. To display more than one categories separated by a comma, use <?php the_cateogry(‘,’);?>.

You can read more about template tags here.

Conditional Tags

The loop can also use some conditional tags to display different types of content. For example, is_home() returns true if the current page you are visiting is a homepage. Other conditions are like is_admin(), is_single(), is_page(), is_category(), is_tag(), is_author(), is_search(), is_404(), has_excerpt().

You can find a complete list of conditional tags at the WordPress official documentation page dedicated to conditional tags.

Multiple Loops

In some cases, you may need to use multiple loops on a single web page. To accomplish this, you have to use the rewind_posts() function before applying the next loop. You can use as many loops you want, but each loop will initiate a separate request to access the database, which can further lead to slow the load time of your page.

Try not to use more than three loops at a single page.

Here is how you can use multiple loops with a rewind_post() function.

<?php
//first loop
if (have_posts()) {
    while (have_posts()) {
        the_post();
        the_title();
        the_content();
    }
}

rewind_posts();

//second loop
if (have_posts()) {
    while (have_posts()) {
        the_post();
        the_title();
        the_content();
    }
}
?>

Although the purpose here was to show you a simple example of minimal multiple loops, the problem with this code is that both loops are displaying the exact same thing. In order to change the output from the loop, we can set the parameters for loops using the WP_Query function.

The WP_Query function

The wp_query() function is a very powerful function of the class WP_Query defined in class-wp-query.php. You can write your custom queries using wp_query() function to interact with the database and display posts based on different parameters. You can directly send the query to the database, but using wp_query is the recommend way to query posts.

Let’s say you want to display posts from a specified category called tutorials.

<?php
// the query
$the_query = new WP_Query('category_name=tutorials');

// The Loop goes here
if ($the_query->have_posts()) {
    echo '<ul>';
    while ($the_query->have_posts()) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    echo 'There are no post to display';
}
wp_reset_postdata();
?>

The wp_reset_postdata() function is used to restore the value of the global $post variable to the current post. It is used when you are customizing the loop using the wp_query() function or creating multiple loops on the same page. It doesn’t accept any parameter and simply resets the post data after the execution of a custom query.

The wp_query is used before the execution of the loop, which is nice as you don’t have to make any changes in the loop itself.

It takes few a list of parameters as an array. Here is another example which will display the Sample Page (WordPress comes with this page by default).

<?php
$args = array(
    'pagename' => 'Sample Page'
);
$q    = new WP_Query($args);

if ($q->have_posts()) {
    while ($q->have_posts()) {
        $q->the_post();
        the_title();
        the_content();
    }
}
?>

You can learn more about the WP Query class here.

In case you have any question regarding the loop, please leave your question in the comment section below, and I will try to answer your questions.

Related Articles