Elegant Themes Blog

Stay up to date with our most recent news and updates

The WordPress Loop Explained For Beginners

Posted on April 22 by in Tips & Tricks | 23 comments

The WordPress Loop Explained For Beginners

The WordPress Loop is the code that WordPress uses to display content on your website.

Take your index.php template, for example. In a basic blogging theme, this template is generally used to display several posts or post excerpts on your home page. The index.php template uses the WordPress Loop in order to do this.

A basic understanding of the WordPress loop is necessary if you want to modify your WordPress design. Even if you do not have experience with PHP or HTML, you should be able to understand how the WordPress Loop is constructed after reading this tutorial.

Understanding the WordPress Loop

The best way to learn about the WordPress Loop is to look at a basic example of how it is used in a WordPress theme. Therefore, let us look at some simple code initially and then I can break down each line to give you a better understanding of what each line does.

Below is an example of a simple WordPress Loop. The code in your own WordPress theme for the loop may be much longer, however it follows the same structure as this.

<?php 
	if ( have_posts() ) :
		while ( have_posts() ) :
			the_post(); 
			//
			// Post Content here
			//
		endwhile; // end while
	endif; // end if
?>

If you have some experience using PHP, the above code will be self-explanatory; however, let us take a closer look at each line for the benefit of those who do not.

The first thing we do is advise your server that we are going to use PHP. We open PHP statement by using <?php.

<?php 

In the next line, we have a basic “if statement” using the have_posts function. The have_posts WordPress function is a boolean function; which means that the result is either true of false.

Therefore, the following line of code effectively says “If there are some posts, display this line of code, if not, do nothing”.

if ( have_posts() ) :

In the next line, we use a while loop. A while loop will execute a piece of code as long as something is true. In this case, we are saying that while there are posts to be displayed, execute the following line of code.

Therefore, if you had configured your WordPress reading settings to display five posts on the home page, the while function would execute the statements contained within the while loop five times and then stop.

while ( have_posts() ) :

We then call the data from the next post by using the WordPress function the_post. This sets up the post and allows us to retrieve any part of the post including the content, the publication date, the author, the category it was published in, and much more later on.

the_post();

Once we have called up our post, we can display anything we want from it. There are over one hundred template tags available that can only be used within the WordPress Loop.

Examples include the_title for displaying the post title, the_content for displaying the post itself, and the_category for displaying the post category.

//
// Post Content here
//

After we have confirmed the information that we want displayed with every post, we close the while loop.

endwhile; // end while

We then close the if statement.

endif; // end if

Finally, we end by closing PHP.

?>

As you can see, when you break down the WordPress Loop, it is very easy to understand.

Examples of the WordPress Loop

In the WordPress codex, WordPress shares the code for the world’s smallest index.php template. As you can see from this code (shown below), all the index.php template contains is a call to the header, the WordPress Loop, a call to a sidebar, and a call to a footer. It perfectly illustrates how simple WordPress can be.

<?php
get_header();
if (have_posts()) :
   while (have_posts()) :
      the_post();
         the_content();
   endwhile;
endif;
get_sidebar();
get_footer(); 
?>

The code for the WordPress Loop looks a little different in most WordPress themes because the information that is displayed is a little different. Examining the WordPress Loop in different designs is therefore a great way of seeing exactly how the loop works in practice.

Below is the code that is used for the WordPress Loop in the index.php template of the current WordPress default theme TwentyFourteen.

As you can see, TwentyFourteen calls a different template for the content area depending on what type of post format is called e.g. a standard post will display different information from video posts and quote posts.

Navigation links are displayed after the last post and a message is displayed to visitors if no posts have been found (they do this by calling the template content-none.php).

<?php
			if ( have_posts() ) :
				// Start the Loop.
				while ( have_posts() ) : the_post();

					/*
					 * Include the post format-specific template for the content. If you want to
					 * use this in a child theme, then include a file called called content-___.php
					 * (where ___ is the post format) and that will be used instead.
					 */
					get_template_part( 'content', get_post_format() );

				endwhile;
				// Previous/next post navigation.
				twentyfourteen_paging_nav();

			else :
				// If no content, include the "No posts found" template.
				get_template_part( 'content', 'none' );

			endif;
		?>

The WordPress Loop is easier to follow in TwentyFourteen and TwentyThirteen because the code for content and meta information is placed in a separate template. It is also a more practical way of structuring code for themes that support post formats.

If we take a look back to the popular theme Twenty Twelve, we can see that the WordPress Loop still calls other template files; however a lot of code remains within the WordPress Loop in the index.php template.

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

			<?php /* Start the Loop */ ?>
			<?php while ( have_posts() ) : the_post(); ?>
				<?php get_template_part( 'content', get_post_format() ); ?>
			<?php endwhile; ?>

			<?php twentytwelve_content_nav( 'nav-below' ); ?>

		<?php else : ?>

			<article id="post-0" class="post no-results not-found">

			<?php if ( current_user_can( 'edit_posts' ) ) :
				// Show a different message to a logged-in user who can add posts.
			?>
				<header class="entry-header">
					<h1 class="entry-title"><?php _e( 'No posts to display', 'twentytwelve' ); ?></h1>
				</header>

				<div class="entry-content">
					<p><?php printf( __( 'Ready to publish your first post? <a href="%s">Get started here</a>.', 'twentytwelve' ), admin_url( 'post-new.php' ) ); ?></p>
				</div><!-- .entry-content -->

			<?php else :
				// Show the default message to everyone else.
			?>
				<header class="entry-header">
					<h1 class="entry-title"><?php _e( 'Nothing Found', 'twentytwelve' ); ?></h1>
				</header>

				<div class="entry-content">
					<p><?php _e( 'Apologies, but no results were found. Perhaps searching will help find a related post.', 'twentytwelve' ); ?></p>
					<?php get_search_form(); ?>
				</div><!-- .entry-content -->
			<?php endif; // end current_user_can() check ?>

			</article><!-- #post-0 -->

		<?php endif; // end have_posts() check ?>

It is best to remember the “Don’t Repeat Yourself” coding principle. By reducing repetition, you can create cleaner, leaner themes that are easier to modify.

Overview

The WordPress Loop is used by WordPress to publish content. In its simplest form, the WordPress Loop simply checks if there are posts or pages to be displayed and then displays them.

By using multiple loops and modifying loops using the WP_Query class, theme developers can design complex website themes. The code for this is sometimes complicated, yet the general principle of how developers create complex themes is based on the basic concept of the WordPress Loop.

In this article, I have explained what the WordPress Loop is for and showed how it is used in themes to display posts and pages.

For more information on the WordPress Loop, please refer to the following pages in the WordPress codex:

I hope you have enjoyed this tutorial. Be sure to subscribe to Elegant Themes if you would like updates of our latest articles.

Article thumbnail image by mejnak / shutterstock.com

23 Comments

  1. Kevin, Thanks for shedding some light on a topic I have been wanting to know more about for some time now. It can be daunting to a non-programmer to make even the smallest php changes and I have broken at least several sites while trying. Now I at least have a basic understanding of how the system works.

  2. For the benefit of those who don’t know any better and think this is normal, it ought to be said that ain’t so. The “loop” is the old time bloggy blog at the core of WordPress that holds it back as a full CMS. That may have been a blessing in disguise, as they say, because WP really is so much more than a “CMS.”

    Still the “Loop” is the thing that most “sucks” about WP. WP_Query is just one of the coping mechanisms added into the core to make it more bearable. Every other CMS I know of has a templating system and lets you just state arbitrarily where you want to put any type of content. But they aren’t WP or 20-30% of the web. So in that sense “it doesn’t matter,” but some day WP is going to have to do things right from the ground up and break backward compatibility to get rid of crap like “the loop.”

  3. Hey, Elegant Themes!

    I’m still waiting for Divi 2.0 and a brand new theme for 2014!

  4. I waited a long time for a clear and simple explanation of the Loop. And here it is, Thank you!

  5. Thanks Kevin. I got my first WordPress “loop” tutorial from Prof Jesse Friedman in his wonderful book “web designer’s guide to WordPress” and I’m glad I invested into it. :D

  6. Loved this. I read your stuff all the time. I could almost skip school reading this blog.

  7. Very nice article for WordPress Loop, deep explanation with great examples. Thanks for share Kevin :)

  8. Nice described, but please reformat pieces of code. It’s very unreadable with such a wide tabs from left, could you reformat it?
    Thanks in advance.

  9. Thanks for the explanation! It’s good to hear a piece of code explained like this, line by line. I have been subscribed to Elegant Themes for over a year now and only recently did I sign up to get your “tips”. I have found them very informative and helpful! Thanks again!

  10. Really nice breakdown. You created a road map for beginners to understand the core of WordPress. Thanks

  11. Thanks for the write up. Indeed it’s an interesting read for any aspiring WP developers.

  12. Thanks for the write up. Indeed it’s an interesting read for any aspiring WP developers.

  13. Where do I find this loop.php in Divi? Is it accessible through the Admin dashboard?

  14. This is a very good tutorial, right now I am working just displaying a custom field (image) using the ACF tutorial so I have to change things up in the loop, this will help me out. Thanks

  15. Just what I am looking for. New to WordPress and needed a little starter like this. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

Join 261,586 Happy Customers And Get Access To Our Entire Collection Of 87 Beautiful Themes For The Price Of One

We offer a 30 Day Money Back Guarantee, so joining is risk-free!

Sign Up Today

Pin It on Pinterest

Share This