Skip to content

Instantly share code, notes, and snippets.

@jchristopher

jchristopher/gist:9233065

Last active Sep 16, 2019
Embed
What would you like to do?
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
<?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
You can’t perform that action at this time.