Recently, I was trying to create Multiple Loops on a WordPress search.php
template and couldn’t find any good tutorials on how to do that. But after a lot of digging around, cobbling together bits of code I found and some experimentation, I finally figured out how to accomplish this task.
Then, I started writing a long tutorial for others to do the same thing, but it got way too unwieldy. So, instead I’m posting up the final code I came up with and will make some comments below on how to customize it for different purposes.
But, before I post this code, I want to emphasize that I’m not an expert at either straight up PHP or WordPress’s PHP functions. This code I came up with might be clunkier than others might like, but it works just fine on my other website, the Underground Film Journal, so I’m happy with it.
Here’s the code:
<?php global $query_string; $query_args = explode("&", $query_string); $search_query = array( /* CUSTOM LOOP PARAMETERS GO HERE */ ); foreach($query_args as $key => $string) { $query_split = explode("=", $string); $search_query[$query_split[0]] = urldecode($query_split[1]); } // foreach $search = new WP_Query($search_query); ?> <?php if ( $search->have_posts() ) : while ( $search->have_posts() ) : $search->the_post(); ?> /* DISPLAY RESULTS IN HTML/PHP HERE */ <?php wp_reset_postdata(); ?> <?php global $query_string; $query_args = explode("&", $query_string); $search_query = array( /* CUSTOM LOOP PARAMETERS GO HERE */ ); foreach($query_args as $key => $string) { $query_split = explode("=", $string); $search_query[$query_split[0]] = urldecode($query_split[1]); } // foreach $search = new WP_Query($search_query); ?> <?php if ( $search->have_posts() ) : while ( $search->have_posts() ) : $search->the_post(); ?> /* DISPLAY RESULTS IN HTML/PHP HERE */ <?php wp_reset_postdata(); ?>
Basically all I am doing here is running the special code that the WordPress Codex says a search.php
template needs two times, but with a wp_reset_postdata();
function in between so that the page resets back to the original search terms for the 2nd loop.
The line that does the heavy lifting, I suppose, is this one:
$search_query = array( /* CUSTOM LOOP PARAMETERS GO HERE */ );
where you input your custom Loop parameters, such as any Category parameters. So, in each block of code you input what your different parameters are for each Loop on the page.
Over on the Underground Film Journal, I used this code to display a selection of Custom Post Types called “Filmmakers” above the regular Search Results. It works fine with that customization as well. If you have any questions, ask below!