SearchWP Documentation

View the installation guide, browse the Knowledge Base, find out about SearchWP’s many hooks

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 supersede SearchWP's relevance weight sorting.
// @link https://searchwp.com/documentation/knowledge-base/custom-field-prioritize-results/
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 ) {
$mod = new \SearchWP\Mod();
$alias = \SearchWP::$index->get_alias();
$meta_alias = 'my_searchwp_sort_' . $post_type;
$mod->column_as( $wpdb->prepare( "(
SELECT meta_value
FROM {$wpdb->postmeta}
WHERE
{$wpdb->postmeta}.post_id = {$alias}.id
AND {$wpdb->postmeta}.meta_key = %s
)", $meta_key ),
$meta_alias );
$mod->order_by( "{$meta_alias} + 0", 'ASC', 2 );
$mods[] = $mod;
}
return $mods;
}, 30, 2 );

Create a Better WordPress Search Experience Today

Never lose visitors to unhelpful search results again. SearchWP makes creating your own smart WordPress search fast and easy.

Get SearchWP Now
Multiple Search Engines Icon