SearchWP Documentation

View the installation guide, browse the Knowledge Base, find out about SearchWP’s many hooks

Define Secondary Order By Sorting for Results with Matching Relevance

There will be times when the relevance of multiple search results is exactly the same, leaving it up to MySQL to decide how to sort those results with matching relevance.

Using a \SearchWP\Mod you can instead specify how you want results with matching relevance to be sorted.

All hooks should be added to your custom SearchWP Customizations Plugin.

<?php
// Add secondary sort to SearchWP results to sort matching
// relevance results by Title in ASC order.
add_filter( 'searchwp\query\mods', function( $mods, $query ) {
global $wpdb;
$mod = new \SearchWP\Mod();
$mod->set_local_table( $wpdb->posts );
$mod->on( 'ID', [ 'column' => 'id' ] );
$mod->order_by( function( $mod ) {
return $mod->get_local_table_alias() . '.post_title';
}, 'ASC', 99 );
$mods[] = $mod;
return $mods;
}, 30, 2 );

Using this snippet we’re telling SearchWP to implement a secondary sorting mechanism to sort results with matching relevance scores by their defined post Title in ASC order.

This is a secondary sorting clause because of the priority set in the order_by() method call which is 99. When setting an order_by() clause in a \SearchWP\Mod each clause is output according to its priority in ASC order.

There is a core default order for all SearchWP queries at priority 10 to sort by relevance in DESC order.

Create a Better WordPress Search Experience Today

Never lose visitors to unhelpful search results again. SearchWP makes creating your own smart WordPress search fast and easy.

Get SearchWP Now
Multiple Search Engines Icon