Last active
February 1, 2021 20:30
-
-
Save jchristopher/5215c2626fff86f3268034a76fadc041 to your computer and use it in GitHub Desktop.
Use a Custom Field as a buoy to supercede SearchWP's relevance weight sorting
This file contains hidden or 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 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 ) { | |
$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