Group search results by source (post type) and set their order
By default SearchWP will return results across all Sources within an Engine, ranked by relevance weight in descending order.
In some cases it’s useful to group results by Source and within each Source group sort results by relevance.
We can utilize a \SearchWP\Mod
to do just that.
All hooks should be added to your custom SearchWP Customizations Plugin.
<?php | |
// Group SearchWP results by Source, sort by relevance within each Source group. | |
// @link https://searchwp.com/documentation/knowledge-base/group-results-by-source-post-type/ | |
add_filter( 'searchwp\query\mods', function( $mods, $query ) { | |
$mod = new \SearchWP\Mod(); | |
$mod->order_by( function( $mod ) { | |
// Search results should be grouped by Sources in this order. | |
// NOTE: _ALL_ Engine Sources must be included here! | |
$source_order = [ | |
'user', | |
\SearchWP\Utils::get_post_type_source_name( 'post' ), | |
\SearchWP\Utils::get_post_type_source_name( 'page' ), | |
]; | |
return "FIELD({$mod->get_foreign_alias()}.source, " | |
. implode( ',', array_filter( array_map( function( $source_name ) { | |
global $wpdb; | |
return $wpdb->prepare( '%s', $source_name ); | |
}, $source_order ) ) ) . ')'; | |
}, '', 1 ); | |
$mods[] = $mod; | |
return $mods; | |
}, 10, 2 ); |
Note: In order for this customization to be fully effective, you will need to customize the $source_order
array with the Source names (in the order you want) and it must include ALL of the Engine Sources.
The snippet above references a utility function to retrieve SearchWP’s internal Source name for post types, the Users source is named user
, and any other Source names must be included as well.
If you would like to conditionally apply this sorting, you can examine the $query
variable to determine whether you want to eject early or apply this \SearchWP\Mod
by returning it.