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; }
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
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.
Sounds good, I’ll look into how to do that. Just found this article here – https://www.relevanssi.com/user-manual/relevanssi_hits_filter/ – that I’ll read through. Thanks for the great support.