Separating Search Results By Post Type

Here is an idea, sort your your loop before it executes. Your current issue is just this. You will see that the type of sorting (if I’m correct where I believe your order is not alphabetical according to post type) is not possible natively, so we need a work-around (even if you just need post types sorted alphabetically, the native way still lack proper functionality). This is where usort() comes in, we can sort the post type post in any order we want. This will be done inside the the_posts filter

I can show you both examples. NOTE: The code sample requires at least PHP 5.4+, which should be your minimum version now. All versions before 5.4 is EOL’ed, not supported and therefor a huge security risk if you are still using those versions.

SORT BY CUSTOM POST TYPE ORDER

add_filter( 'the_posts', function( $posts, $q ) 
{
    if( $q->is_main_query() && $q->is_search() ) 
    {
        usort( $posts, function( $a, $b ){
            /**
             * Sort by post type. If the post type between two posts are the same
             * sort by post date. Make sure you change your post types according to 
             * your specific post types. This is my post types on my test site
             */
            $post_types = [
                'event_type' => 1,
                'post'       => 2,
                'cameras'    => 3
            ];              
            if ( $post_types[$a->post_type] != $post_types[$b->post_type] ) {
                return $post_types[$a->post_type] - $post_types[$b->post_type];
            } else {
                return $a->post_date < $b->post_date; // Change to > if you need oldest posts first
            }
        });
    }
    return $posts;
}, 10, 2 );

SORT BY POST TYPE ALPHABETICAL ORDER

add_filter( 'the_posts', function( $posts, $q ) 
{
    if( $q->is_main_query() && $q->is_search() ) 
    {
        usort( $posts, function( $a, $b ){
            /**
             * Sort by post type. If the post type between two posts are the same
             * sort by post date. Be sure to change this accordingly
             */

            if ( $a->post_type != $b->post_type ) {
                return strcasecmp( 
                    $a->post_type, // Change these two values around to sort descending
                    $b->post_type 
                );
            } else {
                return $a->post_date < $b->post_date; // Change to > if you need oldest posts first
            }
        });
    }
    return $posts;
}, 10, 2 );

Your posts should now be sorted by post type on your search page, that is, if you are not using a custom query in place of your main query. As for your code above, keep it as is, not necessary to make any adjustments to it

Leave a Comment