Chapter 3: The Loop

Now that you have WordPress installed and the theme concept under control, it’s time to look at what really makes the system run. This chapter will teach you about the loop, which basically is a PHP query that talks to WordPress and makes it output the content requested. The chapter starts with some basic loop usage and then branches out to multiple loops and some nice little trickery used within to achieve various effects.

You need to understand the loop to create really cool WordPress sites. Although you won’t need to be an expert, you should grasp what it does. That way, you can research the many functions and features available when you run into a solution that requires custom content output.

Understanding the WordPress Loop

The loop is the heart of WordPress, and it resides in your theme’s template files. Although you can in fact have a theme without the loop, it would make the fluidness of the content handling, such as displaying the latest posts and browsing backward, quite difficult to pull off. Some template files — for example, 404 error pages — don’t have the loop at all, but most do.

Some template tags work only within the loop, so you need to be able to identify it. This is easy, as you will see in the next subsection.

The Basic Loop

If you want to create sites using WordPress, you need to understand the loop. Luckily, the basic one is pretty easy. Here’s what you see to begin with:

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

Get Smashing WordPress: Beyond the Blog, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.