Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

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 file1 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.php1 of your WordPress theme and examine the results in a browser. Hopefully, combining the code comments with the browser output2 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 features3.

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(); ?> • 
	    <?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 © <?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 file1, 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(); ?> • 
	    <?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 © <?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.
  • 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.

About the Author
Jeff Starr = Designer. Developer. Producer. Writer. Editor. Etc.
Banhammer: Protect your WordPress site against threats.

17 responses to “Easily Adaptable WordPress Loop Templates”

  1. 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.

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

  3. 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?

  4. 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.. ;)

  5. 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

  6. Perishable 2008/02/26 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

  7. Karri Flatla 2008/04/24 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!

  8. Perishable 2008/04/27 8:53 am

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

  9. 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?

  10. 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…

  11. Perishable 2008/05/18 7:28 am

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

  12. 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?

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
USP Pro: Unlimited front-end forms for user-submitted posts and more.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.