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

Triple Loop for WordPress

[ WordPress Triple Loop ] 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.

Update: It’s now recommended to use WP_Query and other “looping” techniques to customize the WordPress loop, create multiple loops, and so forth. You can learn more about these techniques in my tutorial, 4 Ways to Loop with WordPress. The basic principles of this article still apply, but you should be using WP_Query instead of query_posts whenever possible.

Intro

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 Upside

The Perishable Press triple loop for WordPress provides several specifically designed features:

  • Each side loop displays posts from any unique category.
  • Each side loop displays any unique number of posts.
  • The main loop may exclude posts from any category.
  • The main loop displays no posts included in either side loop.
  • The main loop displays any unique number of posts.
  • Post views function properly for any post in any loop.

The Downside

The Perishable Press triple loop for WordPress currently encompasses these specific caveats:

  • Archive navigation is only possible for the main loop.
  • The main loop must precede both of the side loops.
  • The “side loops” technically are neither “side” nor “loops”.

Additionally, the main loop will look at the first “x” number of posts, and display only those posts which are not included in either side-loop category. Thus, if the most recent “x” number of posts all belong to either of the side categories, there will be no posts to display in the main loop. Fortunately, there are several relatively simple solutions for this situation, which will be discussed at the end of this article.

The Main Loop

As mentioned, the main loop must appear before the two side loops. Fortunately, the magic of CSS nullifies the restriction imposed by this requirement. Another important point to mention involves the lack of archive navigation (e.g., << previous | next >>) for either of the side posts. Although this may be possible, I have yet to determine an optimal method.

Nonetheless, complete navigation comes standard with the main loop. The side loops work perfectly for displaying the latest “x” number of posts from their respective categories. An elegant solution would be to provide a nice “Read more posts from this category »” link for each side loop display.

Moving along, our first task is to exclude our two chosen side categories from the main loop. Here, we are instructing WordPress to process posts as usual, with the exception that all posts from either side-loop category are ignored. Here are the first three lines of the main 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; ?>

Above, the loop starts with the usual if():while() statement, and then proceeds into a key pair of conditional if statements. The first conditional statement filters out all posts from category 7, while the second does the same for category 8. The remainder of the main loop is expressed as usual, as generalized here, replete with several key elements:

// 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; ?>

The previous loop example includes title, contents, comments, and navigational elements, as well as an else statement issuing a nice “Sorry” message for those awkward, missing-post moments. For more information regarding the WordPress loop, check out the WordPress Codex and 4 Ways to Loop with WordPress.

The Side Loops

As previously noted, the term “side loops” is a bit of a misnomer. Instead of the standard if():while() loop intro, the two secondary loops each begin with get_posts() and foreach():start_wp() statements. With such, the secondary loops function similar to standard loops, but employ a different functional method. As far as calling them “side” loops, well that is just a convenient name, as they may display posts anywhere, not just on the side of a web page.

Now, with the main loop in place, it is time to add the two side loops. Here is the basic setup:

// the second loop
<?php query_posts('cat=7&showposts=3'); ?>
<?php $posts = get_posts('category=7&numberposts=3&offset=0'); 
foreach ($posts as $post) : start_wp(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endforeach; ?>

// the third loop
<?php query_posts('cat=8&showposts=3'); ?>
<?php $posts = get_posts('category=8&numberposts=3&offset=0'); 
foreach ($posts as $post) : start_wp(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endforeach; ?>

Okay, in the previous example, the second loop is querying all posts in category 7 and displaying the first three, beginning with the most recent posts. The second post acts similarly, with the exception that it queries posts from category 8. Each loop also contains a title and excerpt element, included for the sake of demonstrative clarity.

Several important points should be mentioned here. For each of the two side loops, there are two parameters indicating category number, two parameters indicating the number of displayed posts, and one parameter indicating an offset value. For this triple-loop configuration to function properly, it is essential to provide matching parameters for both category and post display number. That is, the values cat=8&showposts=3 must correspond precisely to the values category=8&numberposts=3. Same category, same number of posts to display. Meanwhile, the offset parameter should remain at zero.

Thus, to customize the two secondary loops, simply choose two unique category ID’s and corresponding values specifying how many posts from either category you wish to display.

All Together Now

Now that I have bored you nearly to death with all of the gruesome details, here is the complete code for the Perishable Press triple loop for WordPress:

// 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; ?>

// the second loop
<?php query_posts('cat=7&showposts=3'); ?>
<?php $posts = get_posts('category=7&numberposts=3&offset=0'); 
foreach ($posts as $post) : start_wp(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endforeach; ?>

// the third loop
<?php query_posts('cat=8&showposts=3'); ?>
<?php $posts = get_posts('category=8&numberposts=3&offset=0'); 
foreach ($posts as $post) : start_wp(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endforeach; ?>

That’s all there is to it — copy, paste, and tweak to taste!

Caveat

As previously discussed, the main loop will look at the first “x” number of posts, and display only those posts which are not included in either side-loop category. Thus, if the most recent “x” number of posts all belong to either of the side categories, there will be no posts to display in the main loop. Fortunately, there are several relatively simple solutions for this situation:

  1. Increase the number of posts that are displayed in the main loop via the Admin > Options > Reading panel.
  2. Decrease the number of posts that are displayed in the side loops via step 5a and 5b in the Installation instructions above.
  3. Simply add a few more (or however many it takes) posts to categories appearing in the main loop (i.e., non-side-loop categories).

A Million Loops

With a little imagination, it is easy to envision a case where more than three loops might be required. Fortunately, our method for dishing three WordPress loops may be extrapolated into four WordPress loops, five WordPress, loops, six WordPress loops, …even a million WordPress loops. Well, okay, maybe not. Nonetheless, for any reasonable number of loops, if you have the categories, we have the code!

Here is a hypothetical, generalized example demonstrating “n” number of WordPress loops:

// the first loop
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php if ( in_category('2') && is_home() ) continue; ?>
<?php if ( in_category('3') && is_home() ) continue; ?>
<?php if ( in_category('4') && is_home() ) continue; ?>
<?php if ( in_category('5') && is_home() ) continue; ?>
.                .      .         .            .
.                .      .         .            .
.                .      .         .            .
<?php if ( in_category('n') && is_home() ) continue; ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>

// the second loop
<?php query_posts('cat=2&showposts=3'); ?>
<?php $posts = get_posts('category=2&numberposts=3&offset=0'); 
foreach ($posts as $post) : start_wp(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endforeach; ?>

// the third loop
<?php query_posts('cat=3&showposts=3'); ?>
<?php $posts = get_posts('category=3&numberposts=3&offset=0'); 
foreach ($posts as $post) : start_wp(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endforeach; ?>

// the fourth loop
<?php query_posts('cat=4&showposts=3'); ?>
<?php $posts = get_posts('category=4&numberposts=3&offset=0'); 
foreach ($posts as $post) : start_wp(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endforeach; ?>

// the fifth loop
<?php query_posts('cat=5&showposts=3'); ?>
<?php $posts = get_posts('category=5&numberposts=3&offset=0'); 
foreach ($posts as $post) : start_wp(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endforeach; ?>
.     .     .     
.     .     . 
.     .     . 
// the nth loop
<?php query_posts('cat=n&showposts=3'); ?>
<?php $posts = get_posts('category=n&numberposts=3&offset=0'); 
foreach ($posts as $post) : start_wp(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endforeach; ?>

Well, surely I have worn out my welcome here. Perhaps you will be so kind as to drop a comment to share your particular experience with multiple WordPress loops. Cheers!

About the Author
Jeff Starr = Creative thinker. Passionate about free and open Web.
BBQ Pro: The fastest firewall to protect your WordPress.

50 responses to “Triple Loop for WordPress”

  1. i am just looking at this layout. please excuse the snooping.

  2. Help yourself! — if you have any questions, please don’t hesitate to ask..

  3. i just put two loops in my template on the index.php file and for some reason now the and no longer works properly in the sidebar. it works on the single page, but on the home page the sidebar just doesn’t show up at all – i’m trying to just have certain elements of the sidebar show up on the home page and then different stuff show up on the single post page.

    this is definitely related to the second loop because when i take it out, everything works fine.

    any idea why?

  4. Perishable 2007/01/17 8:56 am

    Sean,

    It is difficult to diagnose issues without seeing the code itself. If multiple loops function properly on single pages, you might try emulating the same code on the index page and working backwards. It sounds like a conflict between the loops and whichever code happens to be different on the two pages. Also, PHP can be very picky — many times the solution lies in something as simple as scripting syntax or even punctuation. If you are totally stuck and need more help, send me an email with some commented code (zipped, please) and I will do my best to help you. My email address is located at the bottom-left corner of our contact page.

  5. James Burns 2007/02/20 11:27 am

    my question is that I really want one of my “side loops” to be at the top of my page just under the header.

    I would like to use it as a feature post, but if the code for the second loop has to follow the main loop how can I get it to come in at the top of my page.

  6. Perishable 2007/02/21 8:27 am

    James,

    From looking at your blog, it appears that you have found a solution? If so, then great. There are also several WP plugins available for "side blogs" — perhaps a search will provide more options for you.. Otherwise, to use the method described above in such fashion, you could always employ a little CSS to reposition the header after the page has been parsed by the server. Just a few ideas.. I hope it helps.

  7. Steve Pierce 2007/05/01 9:10 am

    I am trying out the apathy template but I am getting the error in the right hand column:

    Fatal error: Call to undefined function: c2c_get_recent_posts() in C:\websites\217\ypsinews.com\wp-content\themes\apathy\index.php on line 155 www.ypsinews.com/index.php

    This is running on IIS6. If you have any suggestions they would be most appreciated

    Cheers!

  8. Steve Pierce 2007/05/01 9:14 am

    Whoops, I didn’t enable the two plugins, sorry about that. – Steve

  9. is it possible to use this multiple loop setup to display the main loop on one page, and one of the side loops on a different page… a WP Page?

    I’m looking for a way to split posts into two streams, so to speak, and display on separate pages within the same blog.

    Just wondering if this is the right direction at all…

  10. Perishable 2007/09/18 9:35 am

    richard,

    Not sure if I am understanding you here..

    With WordPress, each page may employ its own loop or series of loops. You can loop through any content on any page(s) you wish. Um, I guess I really need more information to keep going.. ;) If you have examples of the pages or something, it would definitely help..

    (Interesting site, by the way!)

  11. Great tutorial dude you really saved me from google`ing arround all day searching for multiple loop examples

  12. Perishable 2007/10/07 1:04 pm

    My pleasure, Catalin — glad to be of service!

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.