Last active
November 17, 2021 09:47
-
-
Save jchristopher/a5c15c57a9994c92c03acee74e841fad to your computer and use it in GitHub Desktop.
Group SearchWP results by Source, sort by relevance within each Source group
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Group SearchWP results by Source, sort by relevance within each Source group. | |
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 ); |
I really appreciate these snippets, they've helped immensely with the project I'm currently working on.
Is it possible to set a limit to the number of results returned per source? (eg. 5 results per source.)
Thanks in advance!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This seems to be throwing an error with the latest release
substr() expects parameter 1 to be string, object given