apply_filters( 'relevanssi_orderby', string|array $orderby )
apply_filters( 'relevanssi_order', string $order )
Filters the orderby
and order
parameters before Relevanssi sorts posts.
Parameters
$orderby
(string|array) The orderby, either the key as string, or both key and order in array format. Default: relevance
.
$order
(string) The order, asc
or desc
. Default desc
.
More information
By default Relevanssi sorts posts in the descending order of relevance. One way to modify the ordering is to use these filter hooks.
The relevanssi_orderby
hook can be used to set both orderby
and order
by using the array format. This is also the only method to use multiple orderings:
add_filter( 'relevanssi_orderby', function( $orderby ) { return array( 'post_title' => 'asc', 'relevance' => 'desc' ); } );
This would sort posts first by title ascending, then relevance descending. Single parameters can be set also using both filters:
add_filter( 'relevanssi_orderby', function( $orderby ) { return 'post_title'; } ); add_filter( 'relevanssi_order', function( $order ) { return 'asc'; } );
This would set the sorting to post title, ascending.
Possible sorting orders
Any post fields can be used for sorting. These include:
post_title
(shorthandtitle
can be used)post_date
(ordate
)post_modified
(ormodified
)post_parent
(orparent
)post_type
(ortype
)post_name
(orname
)post_author
(orauthor
)menu_order
meta_value
andmeta_value_num
relevance
rand
for random order,rand(123)
for seeded random order (see this KB post for instructions on random search results)
Custom field sorting
Custom field sorting is done with meta_value
and meta_value_num
. The difference between these is that meta_value
values are sorted as strings and meta_value_num
values are sorted as numbers.
The custom field name is taken from the meta_key
query variable. If that does not exist, then Relevanssi checks the meta query and tries to find a key
without a value
.
If you are sorting using fields where not all posts have values, use relevanssi_missing_sort_key
to provide a default value.
Comparisons
For date type fields Relevanssi uses strtotime()
to convert the dates to timestamps and compares those.
For string fields strnatcasecmp()
or strnatcmp()
with mb_strtoupper()
is used, with suitable fallbacks if that is not available.
For post types, the comparison order comes from the relevanssi_comparison_order
filter hook.