Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.
With the popularity of our old WordPress cheat sheet, we've decided to fire up a new batch of these quick pocket guides that you guys n' gals can download, save to your phones for a fast reference, or even print out and keep next to your desk while you're working on customizing WordPress to do your bidding. Today's cheat sheet: The Loop Code Snippet!
The Loop is easily one of the most powerful and crucial pieces of WordPress to understand, and while there's a lot already written about it, it's also just nice to have a quick reference for the loop in the event that you need a fast refresher.
The Short Loop Snippet
This is the quick and dirty version of the loop. No frills, no extra styling, content, categories, tags, or anything like that.
<?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <?php the_content('Read the rest of this entry »'); ?> <?php endwhile; ?> <?php else : ?> //Something that happens when a post isn’t found. <?php endif; ?>
The Long Loop Snippet
This example is a little bit more elaborate. It includes a lot of the core WP tags that you're likely to use in a basic, vanilla, WordPress loop. This means that this one may be a little bit more useful as a starting point... but by no means should this be the limit to what you can do with the loop:
<?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <div class="post" id="post-<?php the_ID(); ?>"> <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2> <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small> <div class="entry"> <?php the_content('Read the rest of this entry »'); ?> </div> <p class="postmetadata">Posted in <?php the_category(', ') ?> <strong>|</strong> <?php edit_post_link('Edit','','<strong>|</strong>'); ?> <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?> </p> </div> <?php endwhile; ?> <div class="navigation"> <div class="alignleft"><?php next_posts_link('« Previous Entries') ?></div> <div class="alignright"><?php previous_posts_link('Next Entries »') ?></div> </div> <?php else : ?> <h2 class="center">Not Found</h2> <p class="center">Sorry, but you are looking for something that isn't here.</p> <?php include (TEMPLATEPATH . "/searchform.php"); ?> <?php endif; ?>
Oh, and we'll be doing our best to keep these sheets updated as WordPress grows into new versions, but if you spot an error (or just want to send some love), let us know in the comments!