November 22, 2014

Multiple Loops on your Main Page – Why and How

First, a definition of “The Loop” from the WordPress Codex:

“The Loop” is a term that refers to the main process of WordPress. You use The Loop in your template files to show posts to visitors. You could make templates without The Loop, but you’d only be able to display data from one post.

Why would I want more than one loop?

  • To have a “Featured” post that is always above all other posts
  • To show a post (or two, or three) of a specific category, or categories on the main page
  • To break the blogging mold and make your theme unique

How do I do it?

This was for a project I’m involved with called Show in a Box. I wanted two loops, the first showing one post from a selected category, and the other looping through all posts while excluding the previously displayed post. I am using the Sandbox theme as a base and will be working with the index.php file specifically. This should work on any theme in theory, but please know that all themes are different, so your code may contain more, or less code than referenced here. As a matter of course, always backup your files before changing anything. Oh, and did I mention that you should backup, backup, backup!

Here goes…so in the original index.php file, you’ll find “The Loop”. This is the chunk of code that WP uses to “loop” through all the posts and display them.

<?php while ( have_posts() ) : the_post() ?>

<?php endwhile ?>

Now, this is the entire code of the index.php file. You’ll see a bunch of code inside “The Loop”, all of that stuff tells WordPress what things to display inside each post. Basically, this small bit of code says “loop through each post and display all of this information inbetween until I find no more posts”.

<?php while ( have_posts() ) : the_post() ?>
<div id="post-<?php the_ID() ?>" class="<?php sandbox_post_class() ?>">
<h2 class="entry-title"><a href="<?php the_permalink() ?>" title="<?php printf(__('Permalink to %s', 'sandbox'), wp_specialchars(get_the_title(), 1)) ?>" rel="bookmark"><?php the_title() ?></a></h2>
<div class="entry-date"><abbr class="published" title="<?php the_time('Y-m-d\TH:i:sO'); ?>"><?php unset($previousday); printf(__('%1$s &#8211; %2$s', 'sandbox'), the_date('', '', '', false), get_the_time()) ?></abbr></div>
<div class="entry-content">
<?php the_content(''.__('Read More <span class="meta-nav">&raquo;</span>', 'sandbox').''); ?>

<?php wp_link_pages('before=<div class="page-link">' .__('Pages:', 'sandbox') . '&after=</div>') ?>
</div>
<div class="entry-meta">
<span class="author vcard"><?php printf(__('By %s', 'sandbox'), '<a class="url fn n" href="'.get_author_link(false, $authordata->ID, $authordata->user_nicename).'" title="' . sprintf(__('View all posts by %s', 'sandbox'), $authordata->display_name) . '">'.get_the_author().'</a>') ?></span>
<span class="meta-sep">|</span>
<span class="cat-links"><?php printf(__('Posted in %s', 'sandbox'), get_the_category_list(', ')) ?></span>
<span class="meta-sep">|</span>
<?php the_tags(__('<span class="tag-links">Tagged ', 'sandbox'), ", ", "</span>\n\t\t\t\t\t<span class=\"meta-sep\">|</span>\n") ?>
<?php edit_post_link(__('Edit', 'sandbox'), "\t\t\t\t\t<span class=\"edit-link\">", "</span>\n\t\t\t\t\t<span class=\"meta-sep\">|</span>\n"); ?>
<span class="comments-link"><?php comments_popup_link(__('Comments (0)', 'sandbox'), __('Comments (1)', 'sandbox'), __('Comments (%)', 'sandbox')) ?></span>
</div>
</div><!-- .post -->

<?php comments_template() ?>
<?php endwhile ?>

Now, in order to tell this loop to only show one post, we have to tell it what category to look in and how many posts from that category to display. So we change that loop code from this:

<?php while ( have_posts() ) : the_post() ?>

…to this…

<?php $my_query = new WP_Query('category_name=featured&showposts=1');
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->ID; ?>

All of the code inbetween goes here

<?php endwhile; ?>

You can see in the code above, I have specified the category “featured” and set it to show 1 post. This could be any category we choose, and further, we could display as many posts from that category as we want.

So, at this point we still only have one loop on the main page, and if we were to view our site now, we would see only one post from the featured category on the main page. But wait, we want to display the rest of the posts underneath this right? So, what do we do? Add another loop on the same page. Here’s the code for the second loop:

<?php if (have_posts()) : while (have_posts()) : the_post();
if( $post->ID == $do_not_duplicate ) continue; update_post_caches($posts); ?>

Some more inbetween code stuff here.

<?php endwhile; endif; ?>

So the post above is the standard WP Loop with some extra parameters. Those extra parameters say “don’t duplicate the post I already have shown in the first loop”, and “update the post cache as you loop through the posts.”

So, that’s it (in a nutshell). I found most of this information here http://codex.wordpress.org/The_Loop#Multiple_Loops and by following some of the links there. I also used some good ‘ole trial and error;) I hope this helps, and if it does, please take a moment to comment and let me know.

What are your favorite WordPress hacks?

WP Modder runs on the Genesis Framework

Genesis Framework

Genesis empowers you to quickly and easily build incredible websites with WordPress. Whether you're a novice or advanced developer, Genesis provides the secure and search-engine-optimized foundation that takes WordPress to places you never thought it could go. It's that simple - start using Genesis now!

Take advantage of the 6 default layout options, comprehensive SEO settings, rock-solid security, flexible theme options, cool custom widgets, custom design hooks, and a huge selection of child themes ("skins") that make your site look the way you want it to. With automatic theme updates and world-class support included, Genesis is the smart choice for your WordPress website or blog.

It's so damn good, I've redesigned all of my sites using Genesis and can confidently recommended it to you here.

Want an Awesome Host? We Recommend HostGator

HostGator for WordPress

Since its establishment in 2002, HostGator has been a world-leading provider of web hosting service. Although their office is in Houston, Texas, they provide top-notch service to clients and developers from over 200 countries internationally with a staff of over 600 employees. They offer Shared, Reseller, VPS, and Dedicated server packages for both beginners and professionals alike.

Each of their shared Web Hosting plans includes 24/7/365 support, a 99.9% uptime guarantee, and a 45-day money-back guarantee. If you would like to learn more, please visit their company page.

I use HostGator for the majority of my own sites and I continually recommend them to my clients. Learn more about HostGator now!

Get our FREE WP Topics Newsletter

The WP Topics newsletter is delivered twice monthly and it's jam packed with information on our WordPress People interviews, WordPress tutorials, new and useful plugins, themes, marketing techniques, and more.

We Respect Your Privacy.

tutorials delivered by email
* indicates required

About Adam W. Warner

I’m a web development consultant and instructor specializing in the use of WordPress and WordPress Multisite.My development philosophy focuses on solutions, education, empowerment, and support for my clients. I will provide you the tools to achieve your project goals, and I will show you how to use those tools.

Comments

  1. awesome.
    this is really important work here.
    I know how we crave to show multiple kinds of videos on the front page that are displayed with different rules.
    so so awesome.

    jay dedman’s last blog post..VIDEO: Open_the_networks

  2. Thanks Jay,

    This is only the tip of the iceberg, stay tuned!

  3. Very Good Adam,
    I would have to mess with it to really get it, but I think you have really documented it well.

    BTW – I got that file. Haven’t looked at it yet, but thanks so much!!
    Milt

  4. Thanks Milt,

    I hope I haven’t missed anything;)

  5. How would you do multiple loops for different types of content. So if you had a static page for your homepage, there is obviously a loop to pull in that static content, but how would you add a loop to that page template to pull in blog posts instead of page posts?

  6. I actually meant to ask how to pull in blog posts IN ADDITION TO a page post all within one page template?

  7. Hi Erik, and thanks for commenting, I’m not sure I understand what you’re asking.

    Can you try and rephrase you’re question and let us know what you’d like to accomplish? Then we can work backwards from your goal and find the parts to give you a solution.

  8. I explained a bit better in the wordpress forum and figured out what I needed (which was basically what your post provides) — http://wordpress.org/support/topic/165447?replies=4. Thanks!

  9. Is this the same as having snippets of numerous post on the home page? They may be in different categories but I want the visitor to the home page to be able to read a small part of each post. Thanks

    Marian Mccanlesss last blog post..Happy New Year!

  10. Hi Marian,

    The short answer to your question is no, this is completely different from what you are trying to achieve.

    Now the long answer…

    What you’re describing is the “the_excerpt” function in the WP world, as opposed to a function named “the_content”.

    When you look at your main blog page, the code that is displaying your posts is displaying “the_content”. That’s why you are seeing the entire post.

    Now, if the code used to display your posts used “the_excerpt” function instead, you would see short summaries of your posts.

    You can force individual posts to use “the_excerpt” by inserting the “More” tag after the first couple of lines of your post. Also, some themes have this built in, some don’t.

    You go here for some further information:
    http://www.sidelinestream.com/blogging/wordpress-excerpts.php

    …and here’s a cool plugin I found for you…
    http://www.dailyblogtips.com/homepage-excerpts-wordpress-plugin/

    Hope that helps. Feel free to use the contact tab if you need more in-depth assistance.

  11. MorseFire says:

    hi there,

    great article! i was wandering though if (or how) it is possible to add pagination to the query posts?

    thanks

  12. MorseFire says:
  13. MorseFire says:

    hi,

    it’s me … again. i discovered another problem. do you have any idea why my comments aren’t working?

    have_posts()) : $my_query->the_post();
    $do_not_duplicate = $post->ID; ?>

    <div class="post" id="post-">

    lorem ipsum
    <a href="">Read more

    hope you know what to do.

    thanks

  14. MorseFire says:

    hm … well … i wander if you have a chance to read the source code somewhere!? cause it just got eaten up by wp …

  15. Hey…the seems broken. Makes it kinda hard to read this tutorial. Thanks :)

  16. Dan Hannigan says:

    Hi, I’m trying to set this up on my main page to where it will display the featured (most recent) post in that category as a thumbnail, and then all the posts beneath it as smaller thumbnails… this is the code I have:


    have_posts()) : $my_query->the_post();
    $do_not_duplicate = $post->ID;?>

    <a href="" rel="bookmark" title="Permanent Link to ">

    Sorry, no posts matched your criteria.
    ID == $do_not_duplicate ) continue; update_post_caches($posts); ?>

    <a href="" rel="bookmark" title="Permanent Link to ">

    Unfortunately it only displays the first post as the large thumbnail, closes it with that “Sorry, No posts matched your critera line” and doesn’t display anything else. I’m not sure what’s going on, I’m also using a wordpress 3.0 build, just because.

  17. The source code dosn’t show properly…

    • Hi Roman,

      Thanks for pointing that out and I apologize, if you read my latest post, you’ll figure out why it wasn’t working;)

      Forgot to activate the plugin that controls that after the move…whoops.

  18. Thanks for this tutorial! I’ve used the first code twice in order to display two different categories. My only problem is that when I click the comments link on one post in one category, it’ll open the comments page for the other post in the other category. I’m not sure if there is a specific code to make sure only one comments page will open, but if there is I was just wondering what it would be or if I’m just not seeing something in the admin panel. I could post my code if there is isn’t. Thanks very much for writing this guide!

  19. thanks for the tips.

    the code doesnt show well on my google chrome.

Trackbacks

  1. [...] Multiple Loops on your Main Page – Why and How | WordPress Modder I wanted two loops, the first showing one post from a selected category, and the other looping through all posts while excluding the previously displayed post. [...]

  2. [...] with a category archive page? One way is to create your own category page template and code in a custom loop, but that’s not really “user-friendly” for most WordPress users. As good news [...]

  3. [...] I’m currently in the process of transforming a very static agency intranet homepage into something more vibrant and news-powered using WordPress and I spent an hour searching for the most fool-proof, direct way to accomplish the display of multiple categories on one page. I thought I’d pass along the best solution I’ve found. [...]

  4. [...] I got the duplicate post detection code from wpmodder.com, a great [...]

Speak Your Mind

*