Skip to content

Instantly share code, notes, and snippets.

@searchwpgists
Created March 9, 2022 16:58
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 searchwpgists/e19132cdba9750bd79686258c6544307 to your computer and use it in GitHub Desktop.
Save searchwpgists/e19132cdba9750bd79686258c6544307 to your computer and use it in GitHub Desktop.
Use a Custom Field as a buoy to supersede SearchWP's relevance weight sorting
<?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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment