Easily Adaptable WordPress Loop Templates

Published Wednesday, November 14, 2007 @ 10:40 am • 18 Responses

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

Hopefully, this basic loop will look very familiar to you. If you are new to WordPress, and would like to gain a better understanding of how the loop works, I highly recommend utilizing the following example. The next example is a carbon copy of the previous loop example, only with several key (X)HTML elements added for clarity. Copy & paste this code into the index.php 1 of your WordPress theme and examine the results in a browser. Hopefully, combining the code comments with the browser output 2 will give you a crystal clear picture of the various features of the WordPress loop.

// any code included here occurs before the wordpress loop and is always displayed
<h1>This text is generated via the h1 element included before the WordPress loop.</h1>
<p>Any code included in this part of the document is processed only once.</p>

<?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
	<h2>This text is generated via the h2 element only if there are posts.</h2>
	<p>Any code included in this part of the document is processed only once.</p>

	<?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
		<h3><a href="<?php the_permalink() ?>">Title: <?php the_title(); ?></a></h3>
		<p>The title of this post is generated before the content of each post.</p>

		<?php the_content(); ?>  // this function displays the content of each post

		// process any code included in this region after the content of each post
		<h4>This is post #<?php the_ID(); ?>, written by <?php the_author(); ?></h4>
		<p>The previous metadata is generated after the content of each post.</p>

	<?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
	<h5>This text is generated via the h5 element only if there are posts.</h5>
	<p>Any code included in this part of the document is processed only once.</p>
	
<?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
	<p>If you are seeing this message, there are no posts to process/display.</p>
	<p>Any code included in this part of the document is processed only once.</p>

<?php endif; ?>

// any code included here occurs after the wordpress loop and is always displayed
<h6>This text is generated via the h6 element included after the WordPress loop.</h6>
<p>Any code included in this part of the document is processed only once.</p>

Once you understand the basic functionality of a basic WordPress loop, it is much easier to customize the look and feel of your WordPress-powered blog. Using built-in WordPress functionality, you can display any information you want, wherever you want. WordPress makes it easy to display vital post data, navigational tools, and many other versatile features 3. To see an example of this in action, replace the previous loop example with the following, fully-pimped version of WordPress looping bliss. This is like the advanced course for understanding the basic WordPress loop. Dig into this, and you will soon be crafting your own, highly specialized loops.

// any code included here occurs before the wordpress loop and is always displayed
<h1><?php echo get_settings('home'); ?>/"><?php bloginfo('name'); ?></a></h1>
<ul class="menu">
	<li><a href="<?php echo get_settings('home'); ?>/">Home Page</a></li>
	<?php wp_list_pages('sort_column=menu_order&depth=1&title_li='); ?>
	<?php wp_register('<li>','</li>'); ?>
</ul>

<?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
	<h2>Here are a few of my recent posts:</h2>

	<?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
		<h3><a href="<?php the_permalink() ?>">Title: <?php the_title(); ?></a></h3>
		<p>Date: <?php echo date("l, F d, Y"); ?> | <?php comments_number(); ?></p>

		<?php the_content(); ?> // this function displays the content of each post

		// process any code included in this region after the content of each post
		<h4>This is post #<?php the_ID(); ?> | Author: <?php the_author(); ?></h4>
		<p>Filed under: <?php the_category(','); ?> | <?php edit_post_link(); ?></p>

	<?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
	<h4><?php posts_nav_link() ?><?php previous_post_link(); ?> &#8226; 
	    <?php posts_nav_link() ?><?php next_post_link(); ?></h4>

<?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
	<p>Sorry, no posts matched your criteria.</p>

<?php endif; ?>

// any code included here occurs after the wordpress loop and is always displayed
<h6>Copyright &copy; <?php echo get_settings('home'); ?>/"><?php bloginfo('name'); ?></a> <?php echo date('Y'); ?></h6>

Observing the patterns involved with the WordPress loop, it becomes easier to look at the code and understand how each part operates and contributes to the whole. With a little practice tweaking and rearranging the various elements, you will improve your ability to manipulate your theme files and gain a better understanding of how WordPress works in general.

The Ever-Popular Mullet Loop

Now that we understand the functionality behind a basic WordPress loop, let’s tweak things a bit and transform our previous example to serve as the ever-popular “mullet” loop. Rather than simply display the full content from each post, the mullet loop displays the full content for only the first post, and then displays only excerpts for all remaining posts. This is a very popular and effective way of highlighting your latest article while providing easy access to recently published posts. To get a better idea of how this works, consider the following:

This paragraph represents the full content of your most recent post.
It will be displayed in its entirety until you publish your next post, 
at which time it will appear beneath this location as an excerpt only.
If we were numbering these hypothetical posts, this post would be #7.
Here comes the dummy text Lorem ipsum.. Lorem ipsum dolor sit amet, a
consectetuer adipiscing elit. Suspendisse nisi. Aliquam ac massa vitae 
ligula dictum congue. Sed elit nulla, eleifend ut, fringilla porttitor, 
tincidunt, nunc. Nam eros nisi, dapibus faucibus, placerat sed, congue 
sed, lectus. Pellentesque vel risus in lacus iaculis auctor. Fusce vel. 
Praesent imperdiet diam ut urna. Phasellus a tortor sit amet maurismet 
vulputate gravida. Suspendisse sed diam. Duis pede ipsum, sagittisorit 
ut, semper in, ultricies at, justo. Sed leo risus, scelerisque quis, a
luctus dictum, vulputate id, mi. Praesent at magna auctor magna dictum
suscipit sagittis. Aliquam gravida facilisis dui. Morbi placerat leros 
est. Nulla a nibh fringilla est eleifend lacinia. Mauris arcu. Ut diam.


This sentence represents an excerpt from post #6, which is displayed 
instead of its full content, thanks to the ever-popular mullet loop.


This sentence represents an excerpt from post #5, which is displayed 
instead of its full content, thanks to the ever-popular mullet loop.


This sentence represents an excerpt from post #4, which is displayed 
instead of its full content, thanks to the ever-popular mullet loop.


This sentence represents an excerpt from post #3, which is displayed 
instead of its full content, thanks to the ever-popular mullet loop.


This sentence represents an excerpt from post #2, which is displayed 
instead of its full content, thanks to the ever-popular mullet loop.


This sentence represents an excerpt from post #1, which is displayed 
instead of its full content, thanks to the ever-popular mullet loop.

To produce this presentational functionality, we have modified our previously discussed, basic WordPress loop according to the following, heavily commented example. As before, read through the comments to gain an understanding of how everything works, and then proceed to the final example for a “marked-up” version to use on a “live” WordPress page.

// any code included here occurs before the wordpress loop and is always displayed

<?php if (have_posts()) : ?>
	<?php $count = 0; ?>

	// if there are posts to display, set the count to zero and begin the loop
	// 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(); ?>
		<?php $count++; ?>

		// for each post, increase the count variable by one and process any code included here
		// the output of any code included here will be displayed above the content of every post

		<?php if ($count == 1) : ?>

			// if this is the first post, process any code that is specified in this region
			// process any code specified in this region before the content of the first post

			<?php the_content(); ?> // display the full content of the first post only

			// process any code specified in this region after the content of the first post

		<?php else : ?>

			// if this is not the first post, process any code specified in this region
			// process any code specified in this region before the content of each post

			<?php the_excerpt(); ?> // display only the excerpt for all other posts

			// for all posts except the first, process this code below each post

		<?php endif; ?>

		// for each post, including the first, process any code included here
		// any code output will be displayed below the content of every 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

Now, let’s wrap up this monster post with a marked up example of the mullet loop. Copy and paste the following code into your index.php file 1, upload to your server, and examine in a browser. And with that, you now have a complete mullet loop template with which to conquer the world, as well as a better understanding of how to create your own looping masterpiece!

// any code included here occurs before the wordpress loop and is always displayed
<h1><?php echo get_settings('home'); ?>/"><?php bloginfo('name'); ?></a></h1>
<ul class="menu">
	<li><a href="<?php echo get_settings('home'); ?>/">Home Page</a></li>
	<?php wp_list_pages('sort_column=menu_order&depth=1&title_li='); ?>
	<?php wp_register('<li>','</li>'); ?>
</ul>

<?php if (have_posts()) : ?>
	<?php $count = 0; ?>

	// if there are posts to display, set the count to zero and begin the loop
	// 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
	<h2>Welcome to the Mullet Loop: Full article first, followed by excerpts</h2>

	<?php while (have_posts()) : the_post(); ?>
		<?php $count++; ?>

		// for each post, increase the count variable by one and process any code included here
		// the output of any code included here will be displayed above the content of every post
		<h3><a href="<?php the_permalink() ?>">Title: <?php the_title(); ?></a></h3>
		<h4>Date: <?php echo date("l, F d, Y"); ?> | <?php comments_number(); ?></h4>

		<?php if ($count == 1) : ?>

			// if this is the first post, process any code that is specified in this region
			// process any code specified in this region before the content of the first post
			<p><strong>Here is the full content of my latest and greatest article:<strong></p>

			<?php the_content(); ?> // display the full content of the first post only

			// process any code specified in this region after the content of the first post
			<h4>Please <a href="<?php bloginfo('rss2_url'); ?>">subscribe</a> to my feed!</h4>

		<?php else : ?>

			// if this is not the first post, process any code specified in this region
			// process any code specified in this region before the content of each post

			<?php the_excerpt(); ?> // display only the excerpt for all other posts

			// for all posts except the first, process this code below each post

		<?php endif; ?>

		// for each post, including the first, process any code included here
		// any code output will be displayed below the content of every post
		<h4>This is post #<?php the_ID(); ?> | Author: <?php the_author(); ?></h4>
		<p>Filed under: <?php the_category(','); ?> | <?php edit_post_link(); ?></p>

	<?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
	<h4><?php posts_nav_link() ?><?php previous_post_link(); ?> &#8226; 
	    <?php posts_nav_link() ?><?php next_post_link(); ?></h4>
	
<?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
	<p>Sorry, no posts matched your criteria.</p>

<?php endif; ?>

// any code included here occurs after the wordpress loop and is always displayed
<h6>Copyright &copy; <?php echo get_settings('home'); ?>/"><?php bloginfo('name'); ?></a> <?php echo date('Y'); ?></h6>

Footnotes

  • 1 Virtually any WordPress theme file may be used here. Keep in mind, however, that the standard loop is designed to operate only once per web page. Thus, placing a loop in your footer.php file, for example, will result in errors if a second loop is encountered elsewhere in the document.
  • 2 For best results, I recommend setting the default number of posts displayed to a relatively large number such as 10 or 15. Displaying a greater number of posts makes it easier to recognize patterns in the code output that may not otherwise be recognized.
  • 3 For additional information on these and many other WordPress features, please refer to the WordPress Codex.

Dialogue

18 Responses Jump to comment form

1Tate

January 8, 2008 at 4:23 pm

I’m in the process of developing a WordPress theme for the first time and I found your post to be helpful and informative.

Thank you.

2Perishable

January 8, 2008 at 10:26 pm

That is great news, Tate! Thank you for the feedback :)

3Seth

January 15, 2008 at 10:42 am

I bumped into your site while looking for help in a special project I’m doing. Maybe you can help me out, if you have time.

I’m trying to figure out if I can make the loop create the following layout (I realize this might be more of a css thing)…

Post 9 | Post 8 | Post 7
Post 6 | Post 5 | Post 4…

And so on. Do you think this is even possible?

4Perishable

January 16, 2008 at 10:52 am

Hi Seth,

Although I don’t have time to really dig into this (I wish I did!), it does seem totally possible using a combination of custom post ordering and CSS. Essentially, you are reversing the post order and applying a non-clearing float to each post container, all within a fixed-width division. Here are five ways to customize post order, and I will leave the CSS to you.. ;)

5Dave

February 24, 2008 at 2:01 pm

Thanks, very helpful…

now… how would I add a loop to display all comments pertaining to a particular post after th epost, followed by the add comment form?

Thanks

6Perishable

February 26, 2008 at 5:09 pm

Hi Dave, although I have not yet encountered (or worked with) a technique for accomplishing this, hopefully one of these related articles will help you devise a solution:

Super Loop: Exclude Specific Categories and Display any Number of Posts
Perishable Press Triple Loop for WordPress

I will definitely be keeping an eye open for other options as well.

Cheers,
Jeff

7Karri Flatla

April 24, 2008 at 9:19 pm

I used your templates above to create a custom blog page to match a theme I also customized via CSS. Before tonight I had never touched PHP and now I think I can do some damage!

Thank you so much! What a helpful resource and tutorial.

Best to you on the web!

8Perishable

April 27, 2008 at 8:53 am

Thank you for the positive feedback — I am glad you found the tutorial helpful! Cheers :)

9Will K

May 15, 2008 at 8:12 pm

I’m using the Mullet loop, excluding one category which I am trying to display within another column after the muller loop.

When I try to display the single category in that subsequent column, all is fine until I create another post, when the new post goes into the column with the excluded category (except the first paragraph!) — as well as the main mullet loop first post — regardless of what category the new post goes into.

I used the std mullet w/ the following code:

<?php query_posts('cat=Moblog&showposts=4'); ?>
<?php $posts = get_posts('category=Moblog&numberposts=4&offset=0');
foreach ($posts as $post) : start_wp(); ?>
<?php the_content(); ?>
<?php endforeach; ?>
<!-- </div> end moblog -->
<?php else : ?>
<?php endif; ?>

What did I do wrong?

10Will K

May 17, 2008 at 7:00 am

Whoa! I got it. Can’t use the category name here — you have to use the category number.

I’ll just have to remember to change category numbers when I move from localhost to live…

11Perishable

May 18, 2008 at 7:28 am

Excellent, Will! I am glad you got it working ;) Thanks for following up your initial comment, btw — much appreciated. Cheers!

12Publix

June 2, 2008 at 4:48 am

Hi,

I was just wondering whether it is possible to change the 55 words limit on posts excerpts? Is there anyway to lower the limit? My blog theme initially had a nice post excerpt feature integrated but because 55 words is too long, I ditched the code and replaced it with a random image code.

Any ideas?

13Perishable

June 2, 2008 at 9:44 am

Sure do — check out the excellent the_excerpt Reloaded. It allows full control over just about everything related to post excerpt generation and display. I use it on many of my blogs.

14Publix

June 2, 2008 at 1:28 pm

Thanks for the link Perishable :) I’ve tried playing with the plugin but somehow I could not get it to work. It seems that the the_excerpt_reloaded function just loaded the_excerpt and ignoring any custom settings.

However, after a few minutes of Googling I found a quick and dirty way of overriding the_excerpt function :)
- Link: Changing the length of the_excerpt() in Wordpress :)

15Perishable

June 3, 2008 at 11:30 am

That works! :)

16Link-Building Andy

July 3, 2008 at 1:12 pm

While it’s not too bad to be able to modify existing themes, I’ve always wanted to be able to create my own wordpress theme from scratch one day. Looks like this post will help me do it. I’m definitely bookmarking this for future references! -Andy

17Perishable

July 4, 2008 at 5:00 pm

Thanks for the feedback, Andy — glad to be of service! ;)

Subscribe to comments on this post


[ Comments are closed for this post. ]

If you have additional information, contact me.

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

heading out of town on a photographic excursion. great way to break up the routine.

Perishable on Tumblr

Office painted a warmish/neutral off-white color. New 2.1...

Tue, 02 Feb 2010


New office digs..


Night view..


Potential..

Office painted a warmish/neutral off-white color. New 2.1 Altec/Lansing speakers for crisp, clear sound. Two new executive desks: one for computer biz and another workspace for drawing, painting, and other offline pursuits. And of course, a big, cushy black office chair to make it all sweet.

Quick Photoshop Reset

Tue, 19 Jan 2010

Very good Photoshop trick to know: If you hold down ALT+CTRL+SHIFT (Mac: CMD+OPT+SHIFT) while starting Photoshop you can reset all settings back to factory default. Very useful if you have problems with some tools or the interface. – http://bit.ly/4A5LJ5

Insane October

Sun, 01 Nov 2009

By far the most insane month of 2009, October included the following activities:

1st week: Trip to the East Coast, beginning with some business in Connecticut.

2nd week: East Coast trip continues with much pleasure in downtown Manhattan.

3rd week: Photo and art excursions with good friend visiting from Portland, OR.

4th week: Marathon book-editing and fine-tuning for Digging into WordPress.

Now that November is here, things remain busy, but I am hoping to get a chance to restore some balance and regain my equilibrium. Of course, the holidays are right around the corner..

Import Feeds to Facebook

Mon, 07 Sep 2009

Seems like a lot of misinformation and confusion out there on how to import and display your feeds on Facebook. Here is what worked for me:

1. In the lower left-hand corner of your Facebook account, click on “Applications” > “Notes”.

2. In the upper mid-right column, click on “Import a blog” in the “Notes Settings” panel.

3. In the “Import an External Blog” panel, enter your feed URL and check the little box.

4. Click the “Start importing” button and then click on “Confirm Import” on the preview page.

That’s all there is to it. Don’t forget to edit your “Notes Privacy” settings to ensure that people can see and comment on your imported feed items.

Once you successfully import your feed(s), they will appear by clicking on the “Notes” button in the left sidebar of your Home page. Also, your timeline or “Wall” will also display the most recent post from each of your feeds as they are published and pulled into Facebook. This makes it easy for your “Friends” to see what you have been up to elsewhere on the Web.

help me in plain english

Mon, 31 Aug 2009

This has got to be the most ironic comment I have ever read:

“hi i dun a stupid noooby mistake and dint think about encrytion i just put a pass in the change pass box and now when i attempt to see my main.php or index.php its sayin password no and error how can i reset back to having no password or were can i edit the bit so that a pass is automattically seen or if not posable how can i make it so i can put in the pass i made at some point so i can login this way? the 3rd is most prefered as this will help me with other projects i am planning as i am a php noob :s plz sum1 hu is clever help me in plain english”

Thanks, “jay” — you made my week with that one.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • kn33ch41: "But for good browsers such as Opera and Safari, most users are quite savvy, understanding the game and always keeping their browsers...
  • Paul: First off great list. Probably the one of the best I've ever seen. I enjoyed your limiting of The Wall, and Dark Side of the Moon. He...
  • kn33ch41: I use method three, and use method four when a selector only requires one property....
  • r-a-y: Great code. Just wondering if, in certain scenarios, a permalink can be longer than 255 characters. I can think of a weird exam...
  • Jeff Starr: Thanks Oliver! Glad you enjoy the book. Thanks for the great feedback :)...
  • Perry: I've read a number of these Image Preloading techniques today and would like to know the best approach to use. I use PHP 5.3 on th...
  • Infographiste PAO: I didn't know that Jeff, that's a kind of great news, usually ppl don't know about no or dofollow so now it's gonna be alright withou...
  • Bill Brown: @Jakub: Of course, there are many ways to bypass the XML declaration issue when you have PHP short tags enabled. Since the intenti...
  • bucabay: AT Jakub ...
  • Jakub Lédl: Oh sh*t, I came back. What happened to that code I posted? Does this CMS remove PHP from comments or what? I now look like an idiot :...

Read more recent comments..

Attention: Do NOT follow this link!