Archived topic
Customize sorting of Search results page
3 replies · Started by John MacKenzie on December 30, 2020
right now the search results page seems to mix and match product, pages and posts randomly in the search results page. How can we set it so products show up first, then posts then pages?
Hi John,
Unfortunately I don't think this is possible without a custom solution which is a bit out of the forum scope here.
I did some Googling and found some posts that help to get you started if you want to give it a shot:
https://wordpress.stackexchange.com/questions/177650/sort-search-results-by-post-type
https://stackoverflow.com/questions/13487594/sort-search-results-by-post-type
https://stackoverflow.com/questions/52508502/wordpress-search-result-page-first-then-post
Alternatively, we can also make it so only products show if it helps:
https://docs.generatepress.com/article/generate_navigation_search_output/#woocommerce-products
Hope this helps :)
thanks!
this seems to have done it thanks for pointing in the right direction
function order_search_by_posttype($orderby){
if (!is_admin() && is_search()) :
global $wpdb;
$orderby =
"
CASE WHEN {$wpdb->prefix}posts.post_type = 'product' THEN '1'
WHEN {$wpdb->prefix}posts.post_type = 'post' THEN '2'
WHEN {$wpdb->prefix}posts.post_type = 'page' THEN '3'
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');
Glad to hear :)