Note: You are viewing the documentation for Version 4View Version 3 Docs

Using a Custom Field to Prioritize Search Results

By default, SearchWP returns search results ordered by calculated relevance weight in descending order.

In other words the most relevant results bubble to the top based on the weights you’ve set on the Engine settings screen for your search engine(s). Having control over attribute relevance directly facilitates control over how search results rank.

SearchWP’s relevance system can be modified to your liking. This article will outline how to use the numeric value of a Custom Field (postmeta) to control the ranking of search results.

This in essence creates a ‘buoy’ that overrides SearchWP’s relevance weight calculation, and will rank results based on their Custom Field value.

With this customization, results with a Custom Field value will rank above those without a Custom Field value. Results with the Custom Field value will be sorted first by that Custom Field value and then by SearchWP’s relevance value. Results without the Custom Field value will be sorted by SearchWP’s relevance value.

See also: Add Relevance Weight to More Recently Published Entries by Date

All hooks should be added to your custom SearchWP Customizations Plugin.

<?php
// Use a Custom Field as a buoy to supercede SearchWP's relevance weight sorting.
add_filter( 'searchwp\query\mods', function( $mods, $query ) {
global $wpdb;
$meta_key = 'my_buoy_meta_key';
// Add the buoy to these post types:
$post_types = [ 'post', 'page', ];
foreach ( $post_types as $post_type ) {
$source = \SearchWP\Utils::get_post_type_source_name( $post_type );
$mod = new \SearchWP\Mod( $source );
$mod->set_local_table( $wpdb->postmeta );
$mod->on( 'post_id', [ 'column' => 'id' ] );
$mod->on( 'meta_key', [ 'value' => $meta_key ] );
$mod->order_by( function( $mod ) {
return $mod->get_local_table_alias() . '.meta_value+0';
}, 'DESC', 5 );
$mods[] = $mod;
}
return $mods;
}, 30, 2 );
Fix keyword search on your site. No coding required!

Now you can utilize all of the content that's gone unrecognized by native WordPress keyword search instantly with SearchWP

Get SearchWP