Part 6: Learning the WordPress Loop

4

With a shell of a WordPress theme on our hands and content in the back end it’s time to tackle the Loop.

The majority of what we learn by building the loop is used when building other pages so be sure to pay close attention.

Resources

To take part in this tutorial you should have

What does an index typically have?

It’s important to consider this, as it will form a readable plan that we can follow. A typical index would have;

  • Post Title
  • Post Metadata
  • Excerpt of content or similar
  • Thumbnail Image
  • A link through to the post, image or header
  • Pagination

And we’ll have built all of this by the end of this post. To do a lot of this we’re going to use a loop to display posts.

Introducing The Loop

By itself, the loop is very simple, it’s essentially a set of instructions. Below is an example of what’s probably the most basic loop possible. It can be extended into quite a beast depending on what your theme needs.

<?php while ( have_posts() ) : the_post(); ?>

<?php endwhile; ?>

We want something a little more featured, so here’s what we’re going to use:

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

<?php endwhile; ?>
<!-- START PAGINATION -->

<!-- END PAGINATION -->
<?php else: ?>
<!-- no posts found -->
<?php endif; ?>

Put this code in your index.php in place of the static HTML, and put a section in as shown

WordPress Functions

The Loop forms a kind of “frame” for content, though will not display posts of it’s own accord, that’s where WordPress functions come in. WordPress has an utter abundance of built-in functions with predefined behavior that take care of the it!

Titles

A function that (by name) needs no explanation, here’s how we’d use it in the loop.

<?php while ( have_posts() ) : the_post(); ?>
  <section>
    <?php the_title(); ?>
  </section>
<?php endwhile; ?>

Which will output the bottom third here:

using the_title in our loop

Our headings are there, but aren’t formatted or styled. Additionally, they aren’t links. Making this happen is a piece of cake, and relies on another WordPress function: the_permalink.

If we just place it anywhere it’ll spit out the post url, which isn’t much use, but keeping this in mind, we can just place it in an anchor tag, and close the anchor after the_title. Let’s add this, and also add some HTML through the loop so everything looks the right way. Check this out:

        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <section>
          <div class="page-header">
            <h1><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
          </div>
        </section>
        <?php endwhile; ?>

We’ve wrapped the heading in the Bootstrap specific HTML and turned title into a link, even using the_title to generate the link’s title. Now, our homepage will look as follows

the titles are linked up

That’s our heading dealt with, onto the rest.

the_content vs the_excerpt

It’s time to choose between these two functions. For this theme, I want to have a snippet of content on the home page and a link to continue reading the content. There’s two ways to do this with functions. We’re going to take a quick gaze over these before making a decision.

the_excerpt displays text from the excerpt field in the post editor, or if you don’t put anything there, the first 55 words. It’s also finished with an ugly […] if no excerpt is specified so it pays to be mindful of this, and the only link through to content is the title, though it’s easy to add one. Here’s an obligatory screenshot

the_excerpt

the_content displays the entire post unless you provide a more tag <!--more--> somewhere. If you do that, it’ll automatically create a ‘(more…)’ link to invite the read in, and that text is easy to modify. The screenshot…

the_content

Considering the above, and looking at the visual, I’m going to use the_excerpt from here on out.

Implementing the_excerpt

Implementing the_excerpt is much the same as putting the post title into action, wrapped in PHP tags and inside the loop, here’s how my loop looks as of now.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
          <div class="page-header">
            <h1><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
          </div>
            <?php the_excerpt(); ?>
        <?php endwhile; ?>

And that’s it, it’s really that easy. Save your index.php and refresh to make sure it’s all working.

Note: the excerpt is automatically placed between <p> tags.

Excerpt Modification

Just a few small things to do here to make our theme look remarkably better.

Removing the_excerpt‘s More: […]

To change from the ellipsis in square brackets, we need to create a simple function like the one below, written in functions.php of course.

function wppro_custom_excerpt_end( $more ) {
	return '...'; //returns just an ellipsis
	//return ''; example: returns nothing nothing
	//return ' <a class="btn btn-small pull-right" href="'. get_permalink( get_the_ID() ) . '">Continue Reading <i class="icon-hand-right"></i></a>'; example: displays a button
}
add_filter('excerpt_more', 'wppro_custom_excerpt_end');

Just like before, we’ve written a function that specifies what we and, and using a filter, hooks into excerpt_more. This will replace the default with just an ellipsis.

Add a Continue Reading Link

In the example above, I’ve also shown how to replace the default excerpt more with a button, however, if a post is less than 55 words (which is pretty unlikely, let’s face it) then it won’t generate. Here’s my solution to have a continue reading button there no matter what

    <?php the_excerpt(); ?>
      <a class="btn btn-small pull-right" href="<?php the_permalink(); ?>" >Continue Reading <i class="icon-hand-right"></i></a>
  </section>

Most noteworthy are the classes on the link – they’re Bootstrap specific – and dictate the shape, size, and where it floats, in this case, normal size, gray, and right. Further, I’ve also used a right hand icon thanks to the excellent Font Awesome, an easy to use iconic font.

our continue reading button

If you’d prefer your button on the left, simply remove the pull-right class!

If you have questions about the included CSS of Bootstrap, please check the documentation or ask in the comments below!

Note: Font Awesome is included with Flatstrap but the official Bootstrap has changed to Glyphicons.

Adding Post Metadata

When referring to post metadata, we think of the author, date published, and category. Continuing the theme of this post, we have several functions that can bring this all together for us.

the_author_posts_link

When you use the_author_posts_link, it pulls out the author name and makes it a link to their author page.

the_category

Spits out the categories to which a post belongs, and makes them links to said categories.

the_time

This will, of course, display the time the post was published. There exists the_date but if you publish multiple times in one day, it will only display for the first post. To get around this we provide some parameters, shown below.

The Business End of Metadata

I want the metadata to sit between the title and the content, within the page-header div, so that it’s above the bottom border of that div. I also want it to be a smaller font size, so there’s some kind of distinction between it, and the excerpt. Below is how my loop now looks.

  <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  <section>
    <div class="page-header">
      <h1>
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
      </h1>
      <small>
        By <?php the_author_posts_link(); ?>,
         in <?php the_category(', '); //separated by a commma and space ?>,
         on <?php the_time('F j, Y'); //DD Month, YYYY format dates ?>
       </small>
    </div>
    <?php the_excerpt(); ?>
  </section>
  <?php endwhile; ?>

This will display an Author link, the categories the post is in (separated by a comma), as well as the date, presented in Month DD, YYYY format, here’s what it looks like.

metadata added below the header but above the excerpt

Building Familiarity with post_class

We need to add another WordPress function: post_class. This provides a unique set of post classes to a tag (section in our case), allowing for very specific CSS styling. Here’s how it’ll look in your loop.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  <section <?php post_class(); ?>>
    <div class="page-header">
      <h1>
.............

And a screenshot of what it actually produces.

post_class in action

It adds classes that are relevant to each post. We’ll be taking advantage of this later, but if you’d like to read up earlier, you can check out post_class on the Codex.

Pagination

We have over 10 posts, and though we can show more than 10 on the homepage, it starts to impact load times and makes for a very, very long page. Naturally, there’s two WordPress functions to handle pagination.

<?php next_posts_link('Next Page »') ?>
<?php previous_posts_link('« Previous Page') ?>

They’ll work and display default text, but I’ve changed it a little with parameters.

Place them underneath the endwhile in your index.php

<?php endwhile; ?>
  <!-- START PAGINATION -->
    <?php next_posts_link('Next Page »') ?>
    <?php previous_posts_link('« Previous Page') ?>
  <!-- END PAGINATION -->
  <?php else: ?>

If you save and refresh, you’ll see that it works but it looks terrible. First of all, the links are smashed next to each other, and they’re at the same horizontal position as the “Continue Reading” button.

bad pagination

It’s really easy to fix this, and rather than write our own code, we’ll use that which Bootstrap provides. First, put the links in a section, then apply the list tags as follows.

  <!-- START PAGINATION -->
    <section>
      <ul class="pager">
        <li class="previous"><?php previous_posts_link('« Previous Page') ?></li>
        <li class="next"><?php next_posts_link('Next Page »') ?></li>
      </ul>
    </section>
  <!-- END PAGINATION -->

This is on page two, as if you’re on page one, only the next posts link displays.

styled and awesome pagination

Ideally we’d have numbers indicating how many pages there are, but that’s beyond this series, and will be tackled in the advanced series.

Summary

That’s all for this tutorial, we’ve built a loop using a vast range of functions, styled it, used functions.php, and some more. Take some time to go through this again if you need, because there’s a lot to take in, and of course if you get stuck, ask your questions!

Table of Contents

Share on Facebook Back to Top

4 Comments

  • Hi, I think in some of the snippets at the beginning the code is not there. It gave me some errors until I figured it out.

    • I can’t add php code here… what I was telling is that the endif is not in the code.

      • Hey, which code sample in particular are you referring to? If it’s the first one, that’s just an example of the simplest loop you can use.

  • Hi. Until this part with loops everything was ok for me.. but this part i don’t understand for example where exactly is that static HTML in the index.php .Some more infos about the exact location of every section that we need to replace, would be very useful . Keep up the good work.

Speak up! Let us know what you think.