WordPress page with two loops

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

This tutorial show how you can have two WordPress loops on a page.  Here we see a custom two-column page where the left column loop and display all posts in the category “humor”.  The right column loops and displays all posts in the category “educational”.

page with two loops

page with two loops

We created a custom page template for this page.  The custom page template name is “Two Columns” and the theme file for this custom template is page-twocolumns.php.  We described how this was done in a previous tutorial.

Continuing from that tutorial, we now add the WordPress looping code to the left column and also to the right column …

two wordpress loops on page

two wordpress loops on page

At the start of the left loop, we create a new instance of WP_Query passing into it selection criteria. We save this instance in $query1 so that we can do a while loop with $query1->have_posts().  Note that get_permalink() and get_the_title() do not have $query1 preceding it because they are not part of the WP_Query object.

Do similar for the loop in the right column but with its own $query2 instance.

It is a good habit that whenever you do a secondary loop with new WP_Query, you call wp_reset_postdata() after the loop.   WordPress codex says …

“Use this function to restore the global $post variable of the main query loop after a secondary query loop using new WP_Query. It restores the $post variable to the current post in the main query.”

The main query being the the main loop is based on the URL request.  The secondary loop is the one we have called.