How do I filter the search results order?

Is there a way I could have my search results show Pages first and posts after the pages?

My site is a business site with a blog, as opposed to the blog being primary. The static pages have all the “here’s what we do” stuff and ideally they would come up first if someone was searching for various services. The blog posts are more light in tone, but they’re more recent so they come up first.

Read More

The search loop is from the Kubrick theme:

<?php if (have_posts()) : ?>
<div class="center">
<div class="padding-bottom">
<h1><?php _e('Our Search Results', 'kubrick'); ?></h1>
</div>
</div>

<?php while (have_posts()) : the_post(); ?>

<div <?php post_class(); ?>>
<h3 id="post-<?php the_ID(); ?>"><a href="<?php the_permalink() ?>"        rel="bookmark" title="<?php printf(__('Permanent Link to %s', 'kubrick'), the_title_attribute('echo=0')); ?>"><?php the_title(); ?></a></h3><?php the_excerpt(); ?>
</div>

<?php endwhile; ?>

<?php else : ?>

<h2 class="center"><?php _e('No luck. Try again?', 'kubrick'); ?></h2>
<?php get_search_form(); ?>

<?php endif; ?>

Could I put something in there to specify that any result from a “page” would be listed before results from a “post”. Or does WP not actually distinguish between pages and posts at that level? Since the static pages are “static” I could use ID’s maybe?

Thanks!

Related posts

Leave a Reply

1 comment

  1. 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.