Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active November 17, 2021 09:47
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 jchristopher/a5c15c57a9994c92c03acee74e841fad to your computer and use it in GitHub Desktop.
Save jchristopher/a5c15c57a9994c92c03acee74e841fad 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.
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 );
@ahbyass
Copy link

ahbyass commented Nov 2, 2020

This seems to be throwing an error with the latest release
substr() expects parameter 1 to be string, object given

@ionofzion
Copy link

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