Posted on

Ordering search results by date

I’m building a directory and would like the oldest posts to automatically display first in the search results, is this possible?

I found out how to add a link that the user can click to sort the results but would like an automatic solution. Can you provide code that can be added to the functions.php or search.php file to accomplish this?

You can easily change the order to using post date from the Relevanssi settings, but that sort is newest first.

Here’s a simple function that will change the order to post date, oldest first. Just add this code to the theme functions.php:

add_filter('relevanssi_modify_wp_query', 'rlv_asc_date');
function rlv_asc_date($query) {
    $query->set('orderby', 'post_date');
    $query->set('order', 'ASC');
    return $query;
}

(The question was asked here.)

  • Hi Mikko,

    I’m trying to sort the search results by meta value for ‘start_date’, but can’t get it working. It just seems to sort by relevancy(?) instead.

    add_filter(‘relevanssi_modify_wp_query’, ‘rlv_asc_date’);

    function rlv_asc_date($query) {

    global $today;

    $query->set(‘meta_query’, array(
    array(
    ‘key’ => ‘start_date’,
    ‘value’ => $today,
    ‘type’ => ‘date’,
    ‘compare’ => ‘>=’
    )
    )
    );
    $query->set( ‘meta_key’, ‘start_date’ );
    $query->set( ‘orderby’, ‘meta_value’ );
    $query->set(‘order’, ‘ASC’);

    return $query;

    }

    To see example results:
    http://www.trekkingpartners.com/?s=Annapurna+Base+Camp&post_type=request

    Any ideas?
    (btw, the above code works fine on archive pages, but just not on search result pages.)

    Thanks,
    Alex