The WordPress loop

When developing WordPress themes, it’s important to know about the loop. The WordPress loop allows you to display multiple posts on a page, such as the index page of a blog. In this article, we will introduce you to the loop.

If you would like more information on creating WordPress plugins, see our tutorial series on creating your first WordPress plugin.

Starting the loop

To begin the loop, simply initiate a PHP while statement, which will run as long as there are posts available to process:

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

Inside the loop

Within the loop, you would call functions like the_permalink(), the_title(), the_content(), and various other WordPress functions that you want displayed for each post on the page.

In this example, we just want to display the post title with a link to the main post, as well as the post content:

<h2><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”Permanent Link to <?php the_title_attribute(); ?>”><?php the_title(); ?></a></h2>
<?php the_content(); ?>

As you can see, we created a link within the title of the post on the first line, then display the content below it.

As this is a loop, it will display this information for each post that you have within WordPress until there are no more posts to process.

Ending the loop

Now that we have started the loop and added our content to the loop, we need to end it. To end the loop, you may use the following code:

<?php endwhile; else: ?> <p><?php _e(‘Sorry, no posts matched your criteria.’); ?></p> <?php endif; ?>

Complete WordPress loop

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”Permanent Link to <?php the_title_attribute(); ?>”><?php the_title(); ?></a></h2>
<?php the_content(); ?>
<?php endwhile; else: ?>
<p><?php _e(‘Sorry, no posts matched your criteria.’); ?></p>
<?php endif; ?>

References

For further technical documentation on the WordPress loop, you may review the WordPress Codex page on the loop.

0 thoughts on “The WordPress loop

  1. If you are looking to build a theme then understanding the WordPress loop is a must. The Loop is responsible for loading the blog posts on the pages where it is called. To understand the basics with examples refer to this post: https://www.cloudways.com/blog/beginners-guide-wordpress-loop/

Was this article helpful? Join the conversation!