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 your site:

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

3 comments Ordering search results by date

  1. 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(
    ‘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:

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


    1. Relevanssi doesn’t support ordering by meta value with orderby. If you want to sort by meta value, you need to sort the results in a ‘relevanssi_hits_filter’ filter function.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *