Skip to content

Instantly share code, notes, and snippets.

@jaybuys
Last active September 22, 2017 06:10
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 jaybuys/61febeb7a3c8bc4ad4e02ff79670bcff to your computer and use it in GitHub Desktop.
Save jaybuys/61febeb7a3c8bc4ad4e02ff79670bcff to your computer and use it in GitHub Desktop.
Functions for custom weighting in Search WP
/*
* SearchWP Filter - Join the postmeta table so we can grab the resource publication date to add weight to it later.
*/
function hnn_searchwp_query_main_join( $sql, $engine ) {
global $wpdb;
if (isset($_GET['test']) && $_GET['test'] == 'true') {
$meta_key = 'publication_date'; // 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 = '{$meta_key}'";
}
echo $sql . '<br/><br/>';
return $sql;
}
add_filter( 'searchwp_query_main_join', __NAMESPACE__ . '\\hnn_searchwp_query_main_join', 10, 2 );
/**
* SearchWP Filter - Add search weight to more recently published resources
*/
function hnn_searchwp_add_weight_to_newer_posts( $sql ) {
global $wpdb;
if (isset($_GET['test']) && $_GET['test'] == 'true') {
$modifier = 25;
$sql .= " + ( 100 * EXP( ( 1 - ABS( ( UNIX_TIMESTAMP( {$wpdb->prefix}postmeta.meta_value ) - UNIX_TIMESTAMP( NOW() ) ) / 86400 ) ) / 1 ) * {$modifier} )";
}
echo $sql . '<br/><br/>';
return $sql;
}
add_filter( 'searchwp_weight_mods', __NAMESPACE__ . '\\hnn_searchwp_add_weight_to_newer_posts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment