Separating search results collectively by type

There’s two options.

The first and probably the easiest option is to run the query twice on the page in each place you want to use it.

// Author Block
while(have_posts()) : the_post();       
    if ( 'book-author' == get_post_type() ) {   
        ?>
        <h2>AUTHOR</h2>
        <?php the_title(); 
    }
endwhile; rewind_posts();

// Book Block
while(have_posts()) : the_post();       
    if ( 'book' == get_post_type() ) {  
        ?>
        <h2>BOOK</h2>
        <?php the_title(); 
    }
endwhile; 

Note: I’ve used rewind_posts() after the first loop which resets the post counter.

The second option would be either filter the query that WordPress executes or sorting the results once you have them, however for this solution you should be fine with the above code.

Leave a Comment