Skip to content

Instantly share code, notes, and snippets.

@searchwpgists
Last active June 22, 2022 09:48
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 searchwpgists/4991781d47270a2ac473c5f00468a00c to your computer and use it in GitHub Desktop.
Save searchwpgists/4991781d47270a2ac473c5f00468a00c to your computer and use it in GitHub Desktop.
Add search weight to more recently published entries that decays over time in SearchWP
<?php
// Add search weight to more recently published entries in SearchWP.
// Weight decays over time and eventually will not add bonus weight.
// @link https://searchwp.com/documentation/knowledge-base/add-relevance-weight-date/
add_filter( 'searchwp\query\mods', function( $mods ) {
global $wpdb;
$weight_adjust = 15;
$mod = new \SearchWP\Mod();
$mod->set_local_table( $wpdb->posts );
$mod->on( 'ID', [ 'column' => 'id' ] );
$mod->relevance( function( $runtime_mod ) use ( $weight_adjust ) {
$alias = $runtime_mod->get_local_table_alias();
return "
( 100 * EXP(
( 1 - ABS( (
UNIX_TIMESTAMP( {$alias}.post_date )
- UNIX_TIMESTAMP( NOW() )
) / 86400 ) ) / 100 )
* {$weight_adjust} )";
} );
$mods[] = $mod;
return $mods;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment