Seperating Custom Post Search Results

You can group posts by type using posts_groupby filter hook:

add_filter('posts_groupby', 'group_by_post_type' );
function group_by_post_type( $groupby )
{
  global $wpdb;
  if( !is_search() ) {
    return $groupby;
  }
  $mygroupby = "{$wpdb->posts}.post_type";
  if( !strlen(trim($groupby))) {
    // groupby was empty, use ours
    return $mygroupby;
  }
  // wasn't empty, append ours
  return $groupby . ", " . $mygroupby;
}

Then in your loop of do something like this:

$last_type="";
$typecount = 0;
while (have_posts()){
    the_post();
    if ($last_type != $post->post_type){
        $typecount = $typecount + 1;
        if ($typecount > 1){
            echo '</div>'; //close type container
        }
        // save the post type.
        $last_type = $post->post_type;
        //open type container
        switch ($post->post_type) {
            case 'post':
                echo "<div class=\"post container\"><h2>posts search result</h2>";
                break;
            case 'page':
                echo "<div class=\"page container\"><h2>pages search result</h2>";
                break;
            case 'custom_type_name':
                echo "<div class=\"custom container\"><h2>custom post type search result</h2>";
                break;
            //add as many as you need.
        }
    }

    //...
    // do your loop 
    //...
}

Leave a Comment