Have one post type show up above any others
By default SearchWP returns results sorted by relevance using the weights as defined in your Engine configuration.
There are some cases where you may want a specific post type to show up first even if its relevance weight is not highest.
We can do that by customizing the way SearchWP calculates relevance, and afford an extraordinary ‘bonus weight’ for any Product that’s returned, causing it to bubble up to the top of the results.
This bonus weight will be applied to all Products, so the sorting of Products will still respect the calculated relevance. Any non-Product result will be sorted by its relevance below any Product that has received the bonus weight.
All hooks should be added to your custom SearchWP Customizations Plugin.
<?php | |
// Give Products extraordinary weight boost to ensure Products show up first. | |
// @link https://searchwp.com/documentation/knowledge-base/post-type-first-top/ | |
add_filter( 'searchwp\query\mods', function( $mods ) { | |
$post_type = 'product'; // Post type name. | |
$source = \SearchWP\Utils::get_post_type_source_name( $post_type ); | |
$mod = new \SearchWP\Mod( $source ); | |
$mod->relevance( function( $runtime ) use ( $source ) { | |
global $wpdb; | |
return $wpdb->prepare( | |
"IF( {$runtime->get_foreign_alias()}.source = %s, '999999999999', '0' )", | |
$source | |
); | |
} ); | |
$mods[] = $mod; | |
return $mods; | |
} ); |
Note the post type name
on line 7 can be changed to any registered post type name to achieve the same result.
See also: Group search results by source (post type) and set their order