Grokking WordPress: The WordPress Loop and Theme Files
There are a lot of people out there using WordPress to run their blog (this one does), and understanding a bit of how it works can go a long way to wrangling it to meet your needs. Recently, I wanted to add several buttons to the bottom of my post pages: buttons to submit the pages to digg, Reddit, and other sites. The trick is, I didn't know how to make changes to just the post pages (read: singles) and not to my index page. This article outlines the basics of how WordPress handles displaying pages, and how you can start customizing it a bit beyond just pluggable themes.
WordPress works in an interesting way: posts are displayed as query results, which means a list of posts that meet certain criteria (either as search results, or time-based, as specified in the URL) are displayed per-page. This can get tricky when you start to dig into the theme code for your site (especially if you're not familiar with PHP). The solution is to learn a little about how WordPress works.
First, when displaying posts, WordPress works by looping through a list of posts that meet the criteria specified, and displaying each (The Loop). This is done by checking if any posts meet the criteria, and if so, to iterate through each and print the title, a blurb about the post, and any other information the designer decides to include. A simple example, from the WordPress Wiki, looks as follows:
-
if (have_posts()) :
-
while (have_posts()) :
-
the_post();
-
the_content();
-
endwhile;
-
endif;
This loop can be used for both your index page, and for individual (single) pages. The only difference is the number of posts returned – your index page, for instance, may have dozens of posts come up when no criteria is specified, while an individual page, with enough criteria to select exactly one posting, will display the entire article. WordPress does all of this in your index.php template file.
For most themes, this is enough: the major difference between a list of posts and an individual page displaying all content for a given post is often that the content is either cut off (with a Read More… link included), or displayed in its entirety. But what if you want to get into further customization? In my case, I had just an index.php file and wasn't quite sure how to add my "post to" buttons (I wanted them to only show up on a complete post page, and not on any list pages). Well, the solution is to copy your index.php file and name it single.php. The single.php temple file is used instead of index.php (when it exists) to display a single posting page.
Using the single.php file, you can customize how your individual story postings will appear without affecting the appearance of other pages (your index page, search results pages, special pages, etc). Hope you found this useful.














