Using The WordPress Loop

The WordPress Loop is a function that grabs posts from your database. It may be the most important function in your WordPress theme development journey. There are many advanced variations of the loop, but in this article we’ll focus on the basic loop, so you can build up from there.

What you will need…

In order to edit your theme, you will need a local development site, or you can edit the theme files on your server using the cPanel File Manager. (It is recommended that you do not edit live site files for a production site.) Creating a local WordPress installation on your computer is outside the scope of this article.

You will also need a plain, bare bones text editor like Notepad, TextEdit, Sublime, or similar. Editing files in a Word document will add all kinds of extra text that will corrupt your file.

How the Loop Works

So how does the loop work? A basic understanding of PHP is important here, but here are the basics.

  • The loops checks for posts.
  • If there are posts, each one will be displayed until there are no more.
  • While displaying the posts, you can add any content or HTML.

The loop does its job best when you match the elements of your post (like the title, date, or other information) with an appropriate HTML tag. For example, your title can be placed within an <h2> tag.

Here is a basic loop with comments:

 <?php // Check to see if we have posts if ( have_posts() ) :          while ( have_posts() ) : // Open a 'while' loop                 the_post(); // Repeatedly grab next post                 the_content(); //Get the content of the post         endwhile; // End the loop endif; // End the 'if' statement ?> 

Here is the same loop with an <h2> tag that contains the title of the post. You may notice we needed to close PHP in order to use HTML code. All HTML code must be used outside of PHP:

 <?php // Check to see if we have posts if ( have_posts() ) :          while ( have_posts() ) : // Open a 'while' loop                 the_post(); // Repeatedly grab next post         ?> // Close PHP         <h2><?php the_title(); ?></h2>          <?php // Open PHP again                 the_content(); // Get the content of the post         endwhile; // End the loop endif; // End the 'if' statement // Close PHP  ?> 

Where does the loop go?

In theory, you can put the loop anywhere you need to generate an index of posts. But typically, the loop will go into the index.php template page, or any pages designated as an index page like Archives, Category pages, and the like.

Leave a Reply