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

(avery) #1

42 PART I • Getting Started with WordPress


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(); ?>

And this is at the end:

<?php endwhile; else: ?>
<p>Some error message or similar.</p>
<?php endif; ?>

Actually, you don’t need that error message part other than in template files that are used to
output errors, but because a lot of themes do have it, it is included here. It can be a “Posts not
found” error or a search result message telling the visitor that that particular query didn’t
return any hits. Technically, the loop starts with while and ends with endwhile, but it is
common for themes to include the if statement as well for error messages and such. It is
included here for convenience’s sake.

What follows is a fully functional loop, with the common template tags for outputting post
content. You’ll find it, or something pretty similar to it, in either the index.php file or a
loop.php file in most themes:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><a href="<?php the_permalink(); ?>" title="<?php
the_title_attribute(); ?>">
<?php the_title(); ?>
</a></h2>
<?php the_content(); ?>
</div>
<?php endwhile; else: ?>
<div class="post">
<h2>Error!</h2>
<p>Something went wrong! Please try again.</p>
</div>
<?php endif; ?>
Free download pdf