Skip to content

Instantly share code, notes, and snippets.

@searchwpgists
Created March 9, 2022 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searchwpgists/49ff05282e0ba8136467222a01c731bb to your computer and use it in GitHub Desktop.
Save searchwpgists/49ff05282e0ba8136467222a01c731bb to your computer and use it in GitHub Desktop.
Group SearchWP results by Source, sort by relevance within each Source group
<?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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment