WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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>

<?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(); ?>

<?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?


share|improve this question
up vote 7 down vote accepted

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.

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.

share|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
Seems to work just as I want! Thank You! – PVA Feb 10 '12 at 17:39

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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