Sort search results by post type

I found the key: SQL CASE Expression

function order_search_by_posttype($orderby){
    if (!is_admin() && is_search()) :
        global $wpdb;
        $orderby =
            "
            CASE WHEN {$wpdb->prefix}posts.post_type="artist" THEN '1' 
                 WHEN {$wpdb->prefix}posts.post_type="post" THEN '2' 
                 WHEN {$wpdb->prefix}posts.post_type="artwork" THEN '3' 
                 WHEN {$wpdb->prefix}posts.post_type="publication" THEN '4' 
            ELSE {$wpdb->prefix}posts.post_type END ASC, 
            {$wpdb->prefix}posts.post_title ASC";
    endif;
    return $orderby;
}
add_filter('posts_orderby', 'order_search_by_posttype');

Leave a Comment