Demystifying The WordPress Loop

The WordPress Loop is a powerful block of code that sits at the heart of most WordPress templates. My purpose today is to explain this key feature of WordPress as easily and quickly as possible.

The loop serves one main purpose – to display posts. It does this by checking to see what content is available for that specific page, and then loops through and displays it.

The loop knows whether to display multiple pieces of content, like for a long-form blog post, or one single piece of content, like on a static page.

This magic loop begins with a simple If statement that checks to see if content is available. If content is available meaning the If statement came back Yes, it moves to a Then statement. This means there’s content to be displayed. So, if content is available, then display it.

Occasionally, you may come across a WordPress loop that has an Else statement included. This creates dynamic content by giving the loop a fallback or alternative should the intended or expected content not be available.

Knowing how to find a loop is helpful, particularly if you need to go in and edit existing themes.

Two Ways to Display A WordPress Loop

Working with the WordPress codex, we can see that there are two viable methods for displaying loops. The first is a shorthand option, while the second is a little longer and more involved.

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

In the example above the conditional statements are divided only by single colons which makes it shorter. The code above begins the loop and WordPress looks for content to display. 

The code below closes this loop and because the beginning and end of the loop itself are divided you can easily nest this throughout your PHP page for multiple loops or nested loops.

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

The alternative to the short-handed loop above is the longer but single-source combined code below:

<?php 
if ( have_posts() ) {
	while ( have_posts() ) {
		the_post(); 
		//
		// Post Content here
		//
	} // end while
} // end if
?>

These are known as conditional statements. The first method is helpful if you have additional markup (HTML, PHP, CSS, etc.) on the page that are you also displaying along with your WordPress posts or content.

There is no limit to the number of WordPress Loops you can include on a page or even in your site wide footer.

Rad Mitkov
Rad Mitkov
Radoslav is a senior motion graphics engineer and designer specializing in 3D modeling prototypes for digital marketing platforms. Rad frequently writes on WordPress, site optimization and cybersecurity topics.