I would like to display search results grouped by post type. I have regular posts, pages,
and a custom post type of product. How would I accomplish this by editing the below code.
The code below just shows all posts and pages right now.
<?php
while (have_posts()) : the_post();
echo "<h1>";
echo $post->post_type;
echo $post->post_title;
echo "</h1>";
endwhile;
?>
This code alters the original search query to order the results by post-type in the order you select. There are other solutions, but this is the only one i found that doesn’t break pagination or requires multiple queries.
In your case, I’d do two things:
WP_Query
call for each remaining post typeFor (1), this would go in your functions.php:
For (2), adapt the code you provided from your template file:
You can re-use this code for each other post type.
It’s best to avoid using
query_posts
… see querying posts without query_posts (even WordPress devs agree).You need to alter the post query to reorder things. You would execute this just before you enter the loop. You can read more about query_posts in the WordPress codex.
http://codex.wordpress.org/Function_Reference/query_posts