How to Search Multiple Custom Post Types and Style Each Post Type Result Differently

This will allow you to search Custom Post Types in addition to regular posts and allow you to show the results differently dependent on post type.

First put a filter in your theme’s function.php file that will group the results by post type.

add_filter('posts_orderby', 'group_by_post_type', 10, 2);
function group_by_post_type($orderby, $query) {
    global $wpdb;
    if ($query->is_search) {
        return $wpdb->posts . '.post_type DESC';
    }
    // provide a default fallback return if the above condition is not true
    return $orderby;
}

Next, pull open your theme’s search.php file and tackle the following code. This example will separate your Blog “post” Blog Post type, and your “product” Products post type.



    post_type){
        $typecount = $typecount + 1;
        if ($typecount > 1){
            echo '
'; //close type container } // save the post type. $last_type = $post->post_type; //open type container switch ($post->post_type) { case 'post': echo "

Blog Results

"; break; case 'product': echo "

Product Search Results

"; break; } } ?>

  • No results found.