Delving into the Loop

WordPress experts talk in hushed tones about “the loop,” which is the heart of
WordPress. Its job is to fetch content from your website’s database, one piece at a
time, until it reaches the post limit (that’s the “Blog pages show at most” option in
the Settings→Reading section of the dashboard).
The loop appears in many templates. WordPress uses it to create the main list of
posts on the home page (index.php), the list of results after a search (search.php),
and the list of articles you see when you browse by category, tag, author, or date
(category.php, tag.php, author.php, and date.php, or archive.php when one of
the former is missing). The loop even appears on Twenty Twelve’s showcase page
(showcase.php), twice—first to grab the featured posts that it puts up top, and again
to grab the recent posts that it shows underneath.

In the following example, you’ll take a look at the loop in the index.php file and
change the way it works by adding a new feature: the ability to highlight recent

Your first task is to prepare your template. You can copy the index.php file into your
child theme folder using an FTP program, or you can use the Orbisius Child Theme
Creator plug-in to copy it for you.

The next step is to dig through index.php to get a handle on what’s going on and
what area you need to change. Overall, index.php has this structure:

<?php get_header(); ?>
<div id=”primary”>
<div id=”content” role=”main”>
[ The stuff for displaying posts goes here. ]
</div><!– #content –>
</div><!– #primary –>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

This boils the template down to its essentials. As you can see, the template calls
other templates to create the page’s header, sidebar, and footer. In the middle of
this action are two <div> elements, and inside them is the heart of the index.php
template and the loop. This is the part you’ll focus on.
The first ingredient here, inside the <div> elements, is a block of conditional logic—
code that tests a condition, and takes different actions depending on whether that
condition is true or false. Essentially, the template here uses PHP to ask a question:
Are there any posts?
Here’s how the template structures the conditional logic:

<?php if ( have_posts() ) : ?>
[ If there are posts, you end up here. ]
<?php else : ?>
[ If there are no posts, this section shows the “sorry” message.]
<?php endif; ?>

The have_posts() function gets the answer to the question, “Are there any posts?”
If there are, the condition is true, and the first section springs into action. That’s the
part you’re interested in. (If there aren’t any posts, the condition is false, and you can
let the template handle it in the usual fashion, by showing an apologetic message.)
So what takes place inside the first section, which runs as long as your site has at
least one post? The code starts by adding a navigation link, if necessary. This is the
link that appears before the post list and lets visitors step forward to newer posts.
(If your guest is already viewing the most recent post, this link doesn’t show up.)
Then the code triggers the loop (shown here in bold), and ends by inserting another
navigation link—the one that lets readers step back to see older posts.

<?php twentytwelve_content_nav( ‘nav-above’ ); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( ‘content’, get_post_format() ); ?>
<?php endwhile; ?>
<?php twentytwelve_content_nav( ‘nav-below’ ); ?>

The actual loop comes down to just three lines. The while and endwhile commands
delineate the start and end of the loop. As long as you have posts, the loop keeps
running. Every time it runs, it grabs a post, using the WordPress function the_post(),
and feeds it to the single line of code inside. This code is less exciting—it simply farms
out the work of displaying the post to one of the content templates you learned
about earlier, using the get_template_part() function.
Although the code doesn’t seem that exciting right now, there’s a lot you can do
if you wedge yourself inside the loop, between the while and endwhile lines. Currently,
there’s just a single line of code there, but you can expand it to suit your
needs. For example, before the code calls get_template_part() to display a post,
you can run some extra code that does something more clever, like change the
post’s formatting based on one of the post details. Examples include making the
post look different based on its category, author, or publication date. The latter is
what this example does.

The final step is to add the code that checks the post’s date and decides whether or
not to highlight it. Here it is, inside the loop you saw earlier. The new code is boldfaced:

<?php while ( have_posts() ) : the_post(); ?>
$postdate = get_the_date(‘Y-m-d’);
$currentdate =
if ($postdate == $currentdate) {
echo ‘<div class=”newpost”>’;
} else {
echo ‘<div>’;
<?php get_template_part( ‘content’, get_post_format() ); ?>
<?php endwhile; ?>


To understand what’s taking place, you need to examine the code one line at a time.
First, it uses a WordPress function named get_the_date(), which returns the date
the current post was published.

$postdate = get_the_time(‘Y-m-d’);

WordPress takes the result from get_the_date() and puts it into a variable (a storage
slot in memory) named $postdate. That way, the code can use the date stored
there at a later time, when the function compares dates.

NOTE It doesn’t matter what you call your variables, as long as you’re consistent. (So you can’t call the
variable $postdate in one place and $date_of_post in another, because you’ll end up creating two separate
variables.) However, your variable names must start with the dollar sign ($), which has the side effect of making
them easily recognizable.

The next line of code creates a second variable, named $currentdate. It stores the
current date, as retrieved by the PHP date() function, which you saw earlier (page
494). Only now the date is returned in a slightly different format, so it matches up
with the publication date format WordPress uses with posts.

$currentdate = date(‘Y-m-d’);

The moment of drama occurs next. An if statement compares the two variables (in
this case, the two dates) to see if the current date matches the publication date (in
other words, to see if the post was published today). If the answer is yes, then the
code adds a new <div> element, with the class name newpost.

if ($postdate == $currentdate) {
echo ‘<div class=”newpost”>’;
If the answer is no, then the code adds a <div> that doesn’t use any class name.
} else {
echo ‘<div>’;

Either way, the code tacks on the closing </div> element at the end of this block of
content, after it inserts the post content into the page.

<?php get_template_part( ‘content’, get_post_format() ); ?>

NOTE This code may seem slightly magical, because it relies on a tight combination of PHP commands
and WordPress functions that you haven’t seen before. Obviously, you wouldn’t be able to cook up this sort of
code on your own. However, you will be able to grab this sort of code from one of the many WordPress recipe
(page 503), and insert it into your templates when you need it. And the more you do that, the easier it’ll
be to recognize the code you want to change, and the more comfortable you’ll be adjusting that code to solve a

Right now, the revised template doesn’t have much of an effect. All it does is add a
<div> element around the post content. However, this <div> gives you a new way to
apply a customized style. You do that by creating a style rule for the newpost class.
Here are the style rules that create the effect shown in Figure 13-17. The first rule
adds the border, spacing, and background color around the post. The second rule
targets the link in the heading, which holds the post title, and gives it large red text.

.newpost {
padding: 8px;
border: 2px solid darkgray;
border-radius: 10px;
background-color: lightyellow;
margin-bottom: 50px;
.newpost h1 a {
font-size: 2.5em;
color: red;

This two-part approach—using the PHP code to add a style, and then defining the
style—is a common technique in theme customization. It gives you the most flexibility,
because you can change the formatting anytime, without editing the template
and wading through the PHP again.

Delving into the Loop

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s