// Order a query by an post type
// You can just use the 'orderby' query argument to order by 'type' (= post type) to order a query by post type,
// but only alphabetically, with the order set to ASC or DESC.
// If you need an arbitrary order, you can use the following:
function order_search_by_posttype( $orderby, $wp_query ) {
global $wpdb;
// filter the correct query by using the original post_type argument as check
if ( $wp_query->query_vars['post_type'] == [
'portfolio',
'product',
'job_listing'
] ) {
// set the new order of the post types
$orderby =
"
CASE WHEN {$wpdb->prefix}posts.post_type = 'job_listing' THEN '1'
WHEN {$wpdb->prefix}posts.post_type = 'product' THEN '2'
WHEN {$wpdb->prefix}posts.post_type = 'portfolio' THEN '3'
ELSE {$wpdb->prefix}posts.post_type END ASC,
{$wpdb->prefix}posts.post_title ASC";
}
return $orderby;
}
add_filter( 'posts_orderby', 'order_search_by_posttype', 10, 2 );