The Ultimate Guide to the WordPress Loop
In this tutorial, I’ll be going over The Loop, and how WordPress uses it to display your posts and pages. Keep in mind, this is slightly more advanced than our previous tutorials. Hopefully you will find this ultimate guide easier to understand than what’s available in the WordPress documentation. Here’s what we will go over:
- A definition of The Loop.
- Basic flow of The Loop.
- Template tags used in The Loop
- What to do after The Loop
- Template file hierarchy
If you want to get a better understanding of how a WordPress theme really works behind the scenes, read on.
Note: This tutorial assumes you’re using a standard WordPress theme, such as the default Kubrick theme. No advanced multiple-loop stuff…yet.
What is The Loop?
You’re probably still wondering what The Loop even is. Basically, it’s what displays the content you see on your homepage, your single posts, pages, archives, search results, and more.
If a user accesses your homepage, archives, or search results – by default, the Loop will display a certain number of posts as defined in your Reading Options.

At the moment, this loop will displays 10 posts per page, which is what I defined Show at most * posts. On single posts and pages – the same basic Loop code will just display just that specific page.
Basic flow of the loop
Let’s break the Loop down into 3 parts.
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
1. What you want displayed in the Loop
<?php endwhile;?>
2. What is displayed when the Loop is over
<?php else : ?>
3. If there’s nothing to display
<?php endif; ?>
If there are posts available in the query, it will start displaying them in a while loop, what is defined in part 1. When the while is over, it will display what is in part 2. If there’s no posts found, or there’s some sort of other 404 error, part 3 gets displayed.
Define Your Own WordPress Loop Using WP_Query
We all know what the WordPress Loop is right? If not, there are many great tutorials around the web that explain the WordPress Loop.
One of the easiest ways to navigate and manipulate the loop is to use the function called query_posts. Nathan Rice calls it a WordPress developers best friend.
When you use query_posts, however, you risk the following:
- Potential to interfere with plugins which make use of the Loop.
- Potential to invalidate WordPress conditional tags.
- Having to deal with resetting, rewinding, offsetting…
I say skip query_posts. In a way you’ll still be using it, but the better (and sometimes easier) technique is to instantiate your own WP_Query object and create your own loop.
Creating Your Own Loop With WP_Query
The first step is to instantiate your own variable using the WP_Query class.
What we’ll be doing in this example is creating a common feature on blogs, which is to display a list of the recent articles.
<?php
$recentPosts = new WP_Query();
$recentPosts->query('showposts=5');
?>
All I’ve done in the above code is defined a variable named recentPosts and instantiated an instance of WP_Query.
I then used a method of WP_Query to start a query (pretty much the same thing as using query_posts). You even use the same usage parameters as query_posts.
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
<!-- do some stuff here -->
<?php endwhile; ?>
Notice the use of the recentPosts variable to start the loop. We utilize two methods of WP_Query, which is have_posts and the_post. You can read more about those two methods on my article Global Variables and the WordPress Loop.
The beauty of this is that once you are inside your own loop, you can use the standard post tags.
The Full Code
Here’s the full code for showing the last five recent posts using your own loop:
<h3>Recent Articles</h3>
<ul>
<?php
$recentPosts = new WP_Query();
$recentPosts->query('showposts=5');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
Perishable Press Triple Loop for WordPress
Two of the themes developed by Perishable Press, Apathy and Information, depend on three WordPress loops to operate as intended. For each of these themes, the three loops consist of two “side” loops and one main loop. The side loops each display posts from one specific category, while the main loop displays posts from every category not specified in the side loops.
There are many different multi-loop configurations currently available for WordPress users. Needless to say, despite a wide variety of available loop setups, implementing a customized multiple loop frequently requires a great deal of time of energy. Certain loop sets accomplish one task, but fail at another, while others refuse to provide enough flexibility in general. Indeed, after countless rounds of trial and error establishing multiple loops, we finally developed the almost-perfect triple-loop configuration.
// the first loop
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php if ( in_category('7') && is_home() ) continue; ?>
<?php if ( in_category('8') && is_home() ) continue; ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php comments_template(); ?>
<?php endwhile; ?>
<?php posts_nav_link('','','« Previous') ?><?php previous_post('« %', '', 'yes'); ?>
<?php posts_nav_link('','Next »','') ?><?php next_post('% »', '', 'yes'); ?>
<?php else : ?>
<p>Sorry..</p>
<?php endif; ?>
Easily Adaptable WordPress Loop Templates
In this article, I present several heavily commented examples of WordPress loops. I have found that many readers appreciate these types of loop examples, as it helps them to understand how the loop works while enabling them to easily copy, paste, and adapt the code for their own purposes. In our first example, we examine a basic WordPress loop. When implemented, this loop will display “x” number of posts, where “x” represents the number specified via the WordPress Admin reading options panel. To use this code, simply copy & paste into your WordPress theme’s index.php file 1 and customize accordingly.
Your Basic WordPress Loop
// any code included here occurs before the wordpress loop and is always displayed
<?php if (have_posts()) : ?>
// if there are posts to display, process any code included here only once
// display any code output from this region above the entire set of posts
<?php while (have_posts()) : the_post(); ?>
// loop through posts and process each according to the code specified here
// process any code included in this region before the content of each post
<?php the_content(); ?> // this function displays the content of each post
// process any code included in this region after the content of each post
<?php endwhile; ?>
// stop the post loop and process any code included here only once
// any code output will be displayed below the entire set of posts
<?php else : ?>
// if there are no posts to display, process any code that is included here
// the output of any code included here will be displayed instead of posts
<?php endif; ?>
// any code included here occurs after the wordpress loop and is always displayed
Coding the WordPress Loop
Have you ever downloaded a WordPress theme with sloppy code?
There’s probably a good chance you have. Either more than 90% of themes have sloppy code or by some astronomically improbable chance, I only ever happen to download themes with sloppy code. I’m hoping to open the eyes of at least a small percentage of theme authors and help usher in a new era of neater code.
I’m going to break down the basics of the WordPress Loop in this post and help you write cleaner themes. I’ll explain each line of code along the way and point out references to the outside information.
I know. I know. A post about The Loop doesn’t sound too exciting, but maybe this is just what we need — a journey back to the basics. Take a look at the example file to see what The Loop should look like. The important thing here is not to focus on the code but to notice how the code is formatted. See the plentiful whitespace? I’d like to see more of that in themes.
The first step: Opening The Loop
Before we display our posts, we have to open The Loop. Most theme authors know how to get this right, which at least shows potential.
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
The WordPress Loop And Adding Content Outside Of It
The WordPress loop is what controls the posts on the page. And like it’s name – it ‘loops’ the content and anything placed within the loop will be repeated until the loop ends.
Sometimes we’ll need to add content to a page that shouldn’t be repeated with every single post displayed (i.e. ads) and in order to do that, we need to know where the WordPress loop begins and where it ends.
For this example, I’ll be using the default WordPress template (Kubrick) index.php file located in the ‘[WP-INSTALL]/wp-content/themes/default/‘ folder.
You’ll see the loop starts around line 7* with:
<?php while (have_posts()) : the_post(); ?>
The give-away? The word ‘while’ – that is the element that tells you the WordPress loop is starting. You can add your information or content above this line and it will not be repeated with each post, instead, it will show before your posts start.
The loop ends around line 20 with:
<?php endwhile; ?>
The give-away? The word ‘endwhile’ – that is the element that tells you the WordPress loop is ending. You can add your information under this line and it will not be repeated with each post, instead, it will show after all of your posts.
Coding the WordPress Loop – Part 1
There are many, many WordPress themes out there that have been coded fairly poorly, some of them are outright disgusting. So I think it is about time that we take a walk down ‘Theme Coding 101′, and go back to the basics of coding a WordPress theme.
This is not the only way to write the WordPress loop, however it should be used a reference point on which to base your loop on, with correct tags and code formatting.
What is the Loop?
Let’s imagine that you didn’t have a skeleton inside you, you basically couldn’t stand up or function, that is exactly what the WordPress loop is, the skeleton of your WordPress installation. The loop cycles through all the posts, grabbing the required data to display them, from the heading, the post content, tags and categories, plus any other information stored with each post.
<!-- Originally found at www.JustinTadlock.com -->
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title('<h2 class="entry-title"><a href="' . get_permalink() . '" title="' . the_title_attribute('echo=0') . '" rel="bookmark">', '</a></h2>'); ?>
<p class="byline">
<span class="author vcard"><?php the_author_posts_link(); ?></span> <span class="sep">|</span>
<abbr class="published" title="<?php the_time(__('l, F jS, Y, g:i a', 'example')); ?>"><?php the_time(__('F j, Y', 'example')); ?></abbr>
<?php edit_post_link(__('Edit', 'example'), ' <span class="sep">|</span> <span class="edit">', '</span> '); ?>
</p>
<div class="entry-content">
<?php the_content(__('Continue reading', 'example')); ?>
<?php wp_link_pages('before=<p class="pages">' . __('Pages:','example') . '&after=</p>'); ?>
</div>
<p class="entry-meta">
<span class="categories"><?php _e('Posted in', 'example'); ?> <?php the_category(', '); ?></span>
<?php the_tags('<span class="tags"> <span class="sep">|</span> ' . __('Tagged', 'example') . ' ', ', ', '</span>'); ?>
<span class="sep">|</span> <?php comments_popup_link(__('Leave a response', 'example'), __('1 Response', 'example'), __('% Responses', 'example'), 'comments-link', __('Comments closed', 'example')); ?>
</p>
</div>
<?php endwhile; ?>
<?php else : ?>
<p class="no-posts"><?php _e('Sorry, no posts matched your criteria', 'example'); ?></p>
<?php endif; ?>
Starting the Loop
The first and easiest part of forming a new WordPress theme.
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
Understanding WordPress Loop
Once you installed your WP blog, it’s just a matter of time before you hear this word: The Loop.
Did you install a plugin? It probably has some advanced functions to be inserted in The Loop. Do you want to insert a banner or a Google ad after the first post (or inside it)? You have to modify The Loop.
Do you want to fully display only the first five posts and show only the title for the remaining ones?
Agan, you have to modify The Loop.
It’s time to learn what is The Loop
Embedding WordPress – Part 1 of 3 – Using “The Loop” anywhere
This is the first of a three part series of tutorials explaining how to use PHP to embed WordPress content anywhere in a website without the use of <iframes> or other questionable methods. If you’re new to PHP, don’t be frightened, as much of the code can be simply copied from the tutorial and used with only minor modifications. If you are impatient and have knowledge of PHP and the WordPress Loop, Part 3 contains sample usage that you’ll likely find adequate.
Introduction:
I wrote these tutorials because there is a dearth of information on the web explaining how to embed WordPress content outside of the blog itself. A secondary goal of these tutorials is to dispel the myth that WordPress is unsuitable for use as a modular content management system.
The goal of these tutorials is to provide guidance on how to embed and use information and functions from WordPress from outside of the blog using clean, search engine friendly methods. These tutorials do not use kludges such as targeting an <iframe> to the WordPress blog or methods such as using PHP’s fopen() function to grab data from the blog engine. Why? Methods like using frames and iframes are inefficient, a nightmare for Search Engine Optimization and may not work on all web browsers. Using PHP’s fopen() function is better, though it still causes unnecessary load on the web server, is far from elegant and is potentially forbidden by your web host.
I have taken care to make certain that the information contained in these tutorials is accurate, however if there is an error, please let me know and I will revise the tutorials as needed. I hope that these tutorials are of use to the WordPress community and look forward to your comments or questions.
Using The Wordpress Loop To Display Custom Content
When I first started using Wordpress and wanted to do some custom things to my theme I discovered the Template Tag system in Wordpress. At first I was overjoyed that they had decided to do things in a template based system, and that they also decided to do things in a pseudo-programming manner. Most other CMS systems require you to essentially alter the underlying engine of the system in order to add or replace existing functions–or at the very least write your entire code accessing the database and such as if you were directly adding to the engine. Wordpress does not do this but instead gives you “hooks” which you can call that then add in your data directly to the stream of output.
I quickly found the header hook, “wp_head” and the footer hook, “wp_footer”, but was dismayed that I couldn’t find “wp_body”. This last hook I assumed would exist so that content could be added at the start of the display area of your page–but alas it didn’t and still doesn’t exist. So what could I do to add some custom content at the start of my index or other pages?
after a little investigation I discovered “loop_start”. This tag is a hook to place content at the beginning of the Wordpress post display loop–the loop that displays all of your posts on your index page. It also technically is called to display even one post, so it’s called on your single.php page when you display an archive post page.
So, this should probably do the trick right? Well, yes, it sort of does. But there’s one problem: The loop can happen multiple times on a page in some themes. Yup, you can re-run the loop to do all kinds of stuff; like displaying the most recent series of posts in a sidebar, or showing posts from only a single category beneath your main posts. There are a ton of different ways theme authors have used the loop to do funky things in custom themes.
How to add a WordPress Mini-Loop to your static front page.
When I decided to make Big Square Dot a part static, part dynamic website, I was at a loss as to how I would go about incorporating my latest blog entry into the home page of Big Square Dot. I did not want to install WordPress into the root directory of www.bigsquaredot.com because I am all about organization and don’t much enjoy the sight of ‘wp-’ files littering my domain’s root folder.
What I did want was a simple way to include the date, headline, and excerpt of the latest entry from the Big Square Blog into the Big Square Dot main page, which is mostly static.
Enter Wordpress’ Mini-Loop and a little bit of trial and error.
The Setup
The WordPress Codex currently has a section up on adding a Mini-Loop to a static front page, but for my purposes, it was incomplete. The Mini-Loop tutorial only gives the code markup for how to include headlines of the latest blog posts on a static page, but I needed more, like the post date and the excerpt.
Before WordPress code can be executed on any static page, the following lines of PHP must be included in the header, above the body start tag.
<?php
define('WP_USE_THEMES', false);
require('yoursite/wp-blog-head er.php');
?>
A (Smarter) Solution for Displaying WordPress Entries on ANY Part of Your Website
I’m going to keep this pretty cut-and-dry. If you guys and gals have any questions, leave your comments and I will see to it that they get answered. Before I start, I would like to reiterate that the following solution should work on any page outside of your WordPress installation directory. The only thing that is involved is PHP/MySQL and your WordPress database. No template tags are needed.
First, we will configure our website database connection, connect to the database, and then select our WordPress database.
<?php
/*Turn off error reporting.*/
error_reporting(0);
//
/*Configure your database connection*/
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpass = 'dbpass';
//
/*Connect to the database.*/
$conn = mysql_connect ($dbhost, $dbuser, $dbpass)
or die
('There was an error connecting to the database.');
//
/*Select your WordPress database.*/
$dbname = 'dbname';
mysql_select_db ($dbname);
Read More … | Download Source Code

RSS Feeds
Feed Comment 




Hey good stuff…keep up the good work!