The WordPress Loop

08/06/2010 in Creative Circus,WordPress

Most people probably haven’t checked out the WordPress Codex pages on The Loop and The Loop in Action. This is a shame, because there’s no more important concept in WordPress. Let’s get it.

The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. Any HTML or PHP code placed in the Loop will be repeated on each post. When WordPress documentation states “This tag must be within The Loop”, such as for specific Template Tag or plugins, the tag will be repeated for each post.

In plain English, this means that the magic of WordPress is the structured way in wich it iterates through posts, template tags, and files. Have you ever seen a really minimalist WordPress site and wondered how they’re excluding all the extraneous visual noise? At the heart of their customized look is a theme that’s only selecting a minimum of content to display for every post. You don’t even have to display a headline on each post if you don’t want to—it’s up to you.

The simplest example of a functional index.php page in WordPress would be as follows:

<?php
get_header();
if (have_posts()) :
   while (have_posts()) :
      the_post();
      the_content();
   endwhile;
endif;
get_sidebar();
get_footer();
?>

It’s surprisingly easy to understand what’s going on in this snippet:

  • Grab our header file
  • While there are posts to display, show each of them
  • Grab our sidebar file
  • Grab our footer file

What’s important to note here is that there is no one file you’d edit to make thorough changes to your WordPress site’s functionality. The theme files are stitched together on the fly, which gives us the ability to structure our code in a very manageable way.

{ 2 comments }

Nick August 6, 2010 at 12:41 am

The loop was probably the scariest part of wordpress to me starting out. I didn’t have a lick of PHP under my belt and it scared me 1/2 to death.

Today I look back at how basic the loop is and how all those long hours of struggling in code has really paid off.

I wish awesome themes like Thesis existed when I was getting my start with Wordpress. :)

Great post man!

Willie Jackson August 6, 2010 at 1:04 am

Isn’t it crazy how simple it looks in retrospect?

Themes like Thesis are good and bad for learning the guts of WordPress, though. So much is wisely abstracted from n00bs, it often take some purposeful digging to understand what’s going on under the hood. I can’t wait to see what this new Loop API lets us to in Thesis though!

{ 3 trackbacks }