Last active
September 16, 2019 19:51
-
-
Save jchristopher/9233065 to your computer and use it in GitHub Desktop.
Create a Custom Field buoy in SearchWP to have posts with that Custom Field be given arbitrary priority (i.e. explicit higher weight) than SearchWP's calculated result weight
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 | |
function my_searchwp_query_main_join( $sql, $engine ) { | |
global $wpdb; | |
$my_meta_key = 'my_search_priority'; // the meta_key you want to order by | |
$sql = $sql . " LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '{$my_meta_key}'"; | |
return $sql; | |
} | |
add_filter( 'searchwp_query_main_join', 'my_searchwp_query_main_join', 10, 2 ); | |
function my_searchwp_query_orderby( $orderby, $engine ) { | |
global $wpdb; | |
$my_order = "DESC"; // use DESC or ASC | |
$original_orderby = str_replace( 'ORDER BY', '', $orderby ); | |
if ( "DESC" === $my_order ) { | |
// Sort in descending order | |
$new_orderby = "ORDER BY {$wpdb->postmeta}.meta_value+0 DESC, " . $original_orderby; | |
} else { | |
// Sort in ascending order; place empties last | |
// @link http://stackoverflow.com/questions/2051602/mysql-orderby-a-number-nulls-last#8174026 | |
$new_orderby = "ORDER BY -{$wpdb->postmeta}.meta_value+0 DESC, " . $original_orderby; | |
} | |
return $new_orderby; | |
} | |
add_filter( 'searchwp_query_orderby', 'my_searchwp_query_orderby', 30, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment