-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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