0

My search results are limited to post types book and author. The following code in search.php displays all author posts first, then all book posts (I asked why post types are separated like that, but got no answer so far):

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

However I want to display these search results in two columns entitled "BOOKS" and "AUTHORS", each in its own div element. This code doesn't allow that, so how can I achieve such division?

  • could you clarify a bit... you say that posts are grouped by type as they should, what is the problem then? just wrap them in divs and apply style that puts them in columns next to eachother... or am i missing something – Bojana Šekeljić Feb 23 '14 at 14:15
  • I see no way to do that with the code I pasted. – drake035 Feb 23 '14 at 15:23
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.