How do I filter the search results order?

You can use the posts_orderby filter to alter the order of returned posts. This will run for every query (front and back), so make sure you ensure you want to alter the order by using is_admin, is_search etc.

In the example below search results are ordered by post type in ascending order (e.g. page then post), and then ordered by post date in descending order.

add_filter('posts_orderby','my_sort_custom',10,2);
function my_sort_custom( $orderby, $query ){
    global $wpdb;

    if(!is_admin() && is_search()) 
        $orderby =  $wpdb->prefix."posts.post_type ASC, {$wpdb->prefix}posts.post_date DESC";

    return  $orderby;
}

Disclaimer: if you have a post type ‘advert’, and this is appears in search results – this will appear before the pages.

The disclaimer above aside this is a relatively cheap way of achieving what you’re after.

Leave a Comment