Support » Themes and Templates » Lesson: Playing with The WordPress Loop

Lesson: Playing with The WordPress Loop

  • Let’s look at the options available in the WordPress Loop. There have been a lot of changes in the new v1.5 Strayhorn with new tags and improved performance.

    The Loop involves PHP code that follows the instructions given by the user (by clicking on a link, for example) to access information from the database, do specific functions developed by the designer involving the data, and then return the “presentation” of the page for the user to see.

    In its most simplest form, The Loop gets information from the database regarding the posts, displays them, and if the post(s) is not found, returns with a response that says “page not found”.

    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <?php the_date('','<h2>','</h2>'); ?>
    <div class="post">
    <h3 class="storytitle" id="post-<?php the_ID(); ?>"><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>
    <div class="meta"><?php _e("Filed under:"); ?> <?php the_category(',') ?> — <?php the_author() ?> @ <?php the_time() ?> <?php edit_post_link(__('Edit This')); ?></div>
    <div class="storycontent">
    <?php the_content(__('(more...)')); ?>
    <?php endwhile; else: ?>
    <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
    <?php endif; ?>

    This simple Loop publishes the story title, the categories the post is filed under, the author’s name, the time of the posting, and includes a function to allow editing, visible only to the user with the user level permitting editing privileges.

    The best function of The Loop is the series of conditional statements, code that asks “if this happens then do this”. These IF/ELSE statements allow The Loop to generate different results based upon the requests being made.

    In a more sophisticated example from the Codex pages describing The Loop comes an example that adds some excitement to The Loop and shows off the IF/ELSE statement. It looks for posts in Category Three and changes the look of the results in that category.

    Within this examples are “comments”, explanations of what is happening that is only viewed in the code and not by the user. They are surrounded by comment codes (<!-- comment -->).

    <!-- Start the Loop. -->
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <!-- The following tests if the current post is in category 3. -->
    <!-- If it is, the div box is given the CSS class "post-cat-three". -->
    <!-- Otherwise, the div box will be given the CSS class "post". -->
    <?php if ( in_category('3') ) { ?>
    <div class="post-cat-three">
    <?php } else { ?>
    <div class="post">
    <?php } ?>
    <!-- Display the Title as a link to the Post's permalink. -->
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <!-- Display the Time. -->
    <small><?php the_time('F jS, Y'); ?></small>
    <!-- Display the Post's Content in a div box. -->
    <div class="entry">
    <?php the_content(); ?>
    <!-- Display a comma separated list of the Post's Categories. -->
    <p class="postmetadata">Posted in <?php the_category(', '); ?></p>
    </div> <!-- closes the first div box -->
    <!-- Stop The Loop (but note the "else:" - see next line). -->
    <?php endwhile; else: ?>
    <!-- The very first "if" tested to see if there were any Posts to -->
    <!-- display. This "else" part tells what do if there weren't any. -->
    <p>Sorry, no posts matched your criteria.</p>
    <!-- REALLY stop The Loop. -->
    <?php endif; ?>

    Now, the challenge is to come up with a variety of examples of how The Loop can be used. How about an example of excerpts shown on the first page, but the whole post on the post page (index.php, single.php, or post.php – whichever is being used to host the main post)? Or an example of excerpts shown on the first page, archives, and categories? Or more conditional Loops that change the resulting information like the above category example? Show off your PHP talents, folks, and let’s see some Loop examples.

Viewing 15 replies - 1 through 15 (of 23 total)
  • From another thread I found that The Loop can be “abreviated” or truncated down into shorthand. Take this example:

    <?php if($post->post_excerpt) :

    turned into a shorthand version as :

    <?php ($post->post_excerpt) ? the_excerpt() : the_content(); ?>

    I didn’t know you could do that! Now a bunch of code that I’m seeing in many of the Themes make sense!

    Got a Loop example that you like?

    Does anyone have a Loop set for going to the “single.php” for single posts so the style sheet can be different? That would be nice to know how to do.

    I know I must not be alone, or I’m making a mountain out of a piece of rock, but why does the The WordPress Loop seem so complicated?

    Let’s say you want to change the style of your site so that excerpts show up on the first page and categories and archives, but you want to be able to click on the excerpt and be taken to the whole post, and have the whole post actually be a separate php file like single.php or post.php. In the excerpt sections, you can either use the excerpt field you filled in on the Manage > Write panel, or have it default to the first 120 words (default number) of the post if you don’t have a specific excerpt.

    One method features an if/else statement with the excerpt first and then the content – but how do you call it to the single.php?

    <?php if($post->post_excerpt) :

    And where does the html and styles go? When this example is posted, it never shows where the titles are supposed to go and how the php code is broken up. Confuses me terribly, how about you?

    Method Two I’ve found has the content first in the if/else statement with the “else” resulting in the excerpt.

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

    Which one is better? Having the post first in the if/else statement or having the excerpt first?

    And then there are all those comments and trackbacks and the “if not found” stuck in there – or should they be? And where and when?

    Can someone give examples of cutting this up into chunks of PHP with HTML stuff in between for styling titles and the displayed works?

    What’s the difference between using $post and (have_posts()? And what about the shorthand version? If there is no HMTL structure and CSS, how does the shorthand method know what to post where and how?

    Help all of us learn more about how this Loop thing works.



    Lorelle, I’m with you on this one. It’s way confusing. What I want are excerpts on the homepage that show the title and date posted, just like the regular posts look like, only with excerpts. The closest I’ve gotten is by

    <?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
    <?php if(is_single()) { ?>
    <?php the_content(); ?>
    <?php } else { ?>
    <?php the_title(); ?>
    <?php the_excerpt(); ?>
    <?php } ?>
    <?php endwhile; ?>

    I’m new to php and WordPress and this little bit of code took me all day to figure out as I cut and pasted it from posts in this forum. It gets me the excerpts and titles on the homepage, but they aren’t clickable or formatted, just plain text. I want to format them so they look like mini versions of a regular post and are clickable to the permalinks … but I can’t figure it out!

    If WordPress can put together a regular post with a clickable title and proper formatting, shouldn’t it be able to automatically do excerpts with clickable permalinks that way, too? I know I’m missing something very obvious, so if you figure it out please take pity on me and let me know.

    “It gets me the excerpts and titles on the homepage, but they aren’t clickable or formatted, just plain text. “

    Won’t happen with the_excerpt(), which strips html from a post’s content when using it as an excerpt. See my the_excerpt Reloaded plugin for an alternative that provides links, etc.

    the_excerpt reloaded looks just like what I need.

    Thanks !

    Okay, there is a little detail needing explaining in the “stripping out HTML” issue.

    If you have HTML in the explicit excerpt (on your Write Post screen), then the HTML will stay. If you use DIVs it will do some strange things. I have HTML in mine and it works, but when I added a DIV to try something different, it worked but it made the first <p> in the section not automatically show up, but the ending one did, so the page wouldn’t validate. Take out the DIV and it worked like a charm.

    This is my Loop that took me two months to finally figure out. I wish I was kidding. And I doubt it’s as good as it could be. It has two IF/ELSE statements. It says:

    * IF there is a explicit excerpt (for the HTML stuff), show it.
    * IF there isn’t an explicit excerpt, take the first 120 words or go until the <!--more--> tag and show it with the Continue Reading link.
    * ELSE end the whole thing.

    I just realized that in all my work, I left out the Page Not Found. I’ll have to add that….more messing around with this!

    <!-- Start of the Loop -->
    <?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
    <?php if ( $post->post_excerpt ) : // If there is an explicitly defined excerpt ?>
    <div class="excerpt-post">
    <h2 id="post-<?php the_ID(); ?>">
    <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>
    <!-- The following DIV has a bug fix for floats called clearfix -->
    <div class="entry clearfix">
    <?php the_excerpt('Because uses explicit excerpt there is no read on statement'); ?>
    </div> <!--end of entry -->
    <!-- <?php trackback_rdf(); ?> -->
    </div><!-- end of excerpt-post -->
    <?php else : // If there is not an explictly defined excerpt ?>
    <!-- This is undefined excerpt from the post, set with the MORE tag goes -->
    <div class="excerpt-post clearfix">
    <h2 id="post-<?php the_ID(); ?>">
    <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>
    <div class="entry">
    <?php the_content('Continue Reading...'); ?>
    <!-- Needs continue reading as this appears -->
    </div><!-- end of entry -->
    <!-- <?php trackback_rdf(); ?> -->
    </div><!-- end of excerpt-post -->
    <?php endif; // End the excerpt vs. content "if" statement ?>
    <?php endwhile; // End the "while" part of the loop ?>

    Oh, and when you click on the link to the story, it goes to the single.php so I can stylize that a little differently from the front page and archives and things. I need the individual post to be different – just a little. The default WordPress Theme (Kubrick) does this, too.

    The thing about the loop I don’t understand is HOW it knows to get the single.php and not recycle the index.php. Must be something about the hierarchy of how it finds files. Wish someone would explain that to help us understand all of this.

    Oh, and the page not found stuff goes between the endif and the endwhile. Sorry about that.

    It’s all based on queries. If the query is for a single post, you get single.php. Clicking on a post permalink creates this URI: “index.php?name=xxxxxx”. That’s a query for a single post which makes is_single() true which causes single.php to load.

    And I screwed up on where the search not found goes. I actually have no idea where it goes.

    As for the is_single(), I don’t have it in my Loop (unless it is hidden) yet when I click on a post in the main page and archives, it goes to the single.php. Should I add the is_single somewhere so this isn’t totally screwed up?

    Thanks. I know a lot of people are going bonkers with this. We need a serious STEP BY STEP instruction on this for the twits like me.

    Look at the end of wp-blog-header.php. That’s where templates are loaded.

    If you have a single.php template in your theme, then using is_single() in the index.php is pointless because it will never be called. If you don’t have a single.php template, then index.php will be used and is_single() will called in there. It all depends on how the theme author wants to organize templates.

    So this is where they are hiding! Thanks, Ryan!

    So in this article about the template hierarchy on the Codex, this is the file that gives the information that makes this hierarchy possible?

    Yeah. The code at the end of wp-blog-header implements the hierarchy described in that article.

    Hey, Ryan, can you list a few examples of how the Loop is used to generate different content? Before this gets turned over to the dusty threads department or brought into the Codex, we need more examples of using the Loop.

    Here are a few Loop style requests I’ve seen on the forums:

    * Show Excerpts on categories 1, 2, and 3 but full posts in categories 4 and 5

    * Show full posts on front page but excerpts on categories

    * Show HTML on specific categories from within the Loop not on category or archives

    * If post in specific category, then return unique page (Like if a post is in category 4, and when it is clicked, it will go to a single.php page that might be called postcat-4.php to display its single posts with a different look.)

    * Loops that involve the use of the new PAGE feature

    Some of these might be pipe dreams, and they are only the surface of possiblities, but if they are possible, I know people would love the examples.

    And if not you….anyone who knows how to generate this amazing if/else loop statements. Come on folks, display your Loops!

    Add to that list:

    * Loops that set only specific categories for the “home” front page

Viewing 15 replies - 1 through 15 (of 23 total)
  • The topic ‘Lesson: Playing with The WordPress Loop’ is closed to new replies.