I need to sort my search results by custom post type. the problem: the order is custom.
I do have 5 different post types and i got the order like so:
- artist
- artwork
- page
- post
- publication
I’d like the order to be like this:
- artist
- post
- artwork
- publication
- page
Here is what I have so far, the elements are grouped by their post type and get sorted by title. Wonderful. Now all I need is the custom ordering.
Any hint?
add_filter( 'posts_orderby', 'order_search_by_posttype', 10, 2 );
function order_search_by_posttype( $orderby ){
global $wpdb;
if( ! is_admin() && is_search() ) :
$orderby = "{$wpdb->prefix}posts.post_type ASC, {$wpdb->prefix}posts.post_title ASC";
endif;
return $orderby;
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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');
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0