Blog Posts

The WordPress Loop

08 Jul The WordPress Loop

Learning how to edit your theme is just the beginning of all the cool things you can do with WordPress. To take things to the next level, the most important thing to understand is the WordPress loop. The WordPress loop is a line of code that magically loops through all the post types you specify. If you don’t specify anything (as is usually the case) the WordPress loop will just fall back to smart defaults.

For now, we’ll just take a look at it’s syntax, the defaults, and understanding a bit about what goes on. Later we’ll look at changing the query to manipulate the different posts that are displayed for, say, a custom page template.

The WordPress loop appears in just about every theme file (except for the header, footer, and sidebar), or some variation of it. It looks something like this:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

In short, that says: if there are posts, lets loop through them and display them. For pages, it will only loop through this once. But for archives, and other templates it will loop through it multiple times, executing the HTML within the loop.

The loop ends with this line of code:
<?php endwhile; endif; ?>

So all HTML/PHP that is within those two lines of code will be executed one or multiple times, should there be posts to display.

There are also a number of functions that can only be called within the WordPress loop. One such example is the_content(); if that is called outside the loop, it won’t output anything. Called, inside the loop, however it will output the content for that post or page.

To see a list of common functions see “An Introduction to PHP: How to Edit Your WordPress Theme.

Understanding the WordPress loop is a bit more complex than this, but know that WordPress uses smart defaults to create the correct looping structure. Later, we’ll see how to manipulate the output of the loop.

Tags:
,
No Comments

Leave a Reply