5

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.

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!

12

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.

| improve this answer | |
  • Hi Stephen: this sounds like what I want - Thank You! But where do I place this filter? In the search loop I posted? (If so, after what?) In the functions.php? – PVA Feb 10 '12 at 1:26
  • Place it inside functions.php – Stephen Harris Feb 10 '12 at 8:21
  • How can i order by custom_field like if i have 'discount_price' which contains price in text for book records – Ashish v Oct 23 '18 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.