Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

46 PART I • Getting Started with WordPress


USING THE LOOP


Now that you’ve established where you need the loop (in post listings, no matter if it is one or
several posts) and that you can run several at once, the question becomes how to use the loop
most effectively. For one thing, maybe you don’t want to display the full post in your category
listings — maybe you just want an excerpt. This brings you back to the template tags, and the
ones that control the output of the loop.

This section takes a quick look at the most frequently used tags. Chances are, you’ll want to
display and link the title of the various posts. This little code snippet is present in just about
every theme’s template files that list several posts, and sometimes in templates that just
display one as well:

<h2>
<a href="<?php the_permalink(); ?>" title="<?php
the_title_attribute( array(
'before' => 'Permalink to: ',
'after' => '')
);
?>">
<?php the_title(); ?>
</a>
</h2>

It’s really simple: Using the tags for outputting the post title, you display just that. Around the
title is a traditional hyperlink, getting its href value from <?php the_permalink();?>,
which of course is the permalink to the post in question. You’ll get a proper title for the
hyperlink using the_title_attribute(), which returns the title of the post. In this case,
you have added an array of settings, adding the text Permallink to: in front of the title
and nothing at all after it. You can use the_title_attribute() as is, in which case it will
return just an escaped version of the title, as opposed to the_title(), which will return the
whole title.

To output some content, you use either one of these two template tags:

<?php the_content() ;?>
<?php the_excerpt() ;?>

The first tag outputs the full post content, unless you’re on a page listing several blog posts. In
that case, it outputs the content until the point where the <!--more--> tag is inserted; if
that tag is not used, the full post is displayed (see Figure 3-1). If you’re a WordPress user, you
know all about that one; it is the More button in the Text editor, inserting a Read More link.
Free download pdf