WordPress Tip: How to display multiple loops on the same page
I absolutely love wordpress. In case you are not familiar with it, it’s an open source publishing system originally intended for blogs, but has grown into one of the most robust and user-friendly CMS (content management systems) tools on the market. Granted, it still takes skill and experience to design and develop for it but it has really become a favorite of mine. So, I thought I’d start offering up little tips and tricks that I’ve been learning along the way. Being an open source tool, I think it’s imperative that we share our experience with this great tool because, as I’m finding out on a daily basis, there’s always multiple ways to do everything and so much to learn.
Today’s tip is how to display multiple loops the same page. By default, the wordpress loop (ie. the code that queries the database to display your posts) handles one list. But, here is an easy way to do multiple loops on the same page. This is especially useful when you have multiple categories that you’d like to highlight on your page.
On your “index.php” template (or any of your page templates, for that matter. NOTE: this only works directly on your page template files, you can’t insert it from the wordpress admin into the content of your pages) just paste the following code which uses “WP_Query”:
<ul><?php $my_query = new WP_Query('category_name=InsertCategoryNameHere&posts_per_page=5'); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID; ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul>
As you can see, all you do is replace the “InsertCategoryNameHere” with your intended category name (when using permalinks), and place it wherever on your page you want the list to go. You can also control how many links you want to display (in this case I chose 5). Then you just do normal css styling of your lists. For your next loop, again just replace the category name and place it wherever you want on your page.
I hope that helps. If you have any questions please feel free to comment below.