Skip to content

Instantly share code, notes, and snippets.

@searchwpgists
Created March 9, 2022 17:08
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/928851c351034383509f35ac02df41cd to your computer and use it in GitHub Desktop.
Save searchwpgists/928851c351034383509f35ac02df41cd to your computer and use it in GitHub Desktop.
Add search weight to more recently published entries in SearchWP.
<?php
// Add search weight to more recently published entries in SearchWP.
// @link https://searchwp.com/documentation/knowledge-base/add-relevance-weight-date/
add_filter( 'searchwp\query\mods', function( $mods ) {
global $wpdb;
$mod = new \SearchWP\Mod();
$mod->set_local_table( $wpdb->posts );
$mod->on( 'ID', [ 'column' => 'id' ] );
$mod->relevance( function( $runtime ) use ( $wpdb ) {
return "
COALESCE( ROUND( ( (
UNIX_TIMESTAMP( {$runtime->get_local_table_alias()}.post_date )
- (
SELECT UNIX_TIMESTAMP( {$wpdb->posts}.post_date )
FROM {$wpdb->posts}
WHERE {$wpdb->posts}.post_status = 'publish'
ORDER BY {$wpdb->posts}.post_date ASC
LIMIT 1
)
) / 86400 ), 0 ), 0 )";
} );
$mods[] = $mod;
return $mods;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment