Skip to content

Instantly share code, notes, and snippets.

@searchwpgists
Created March 9, 2022 17: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 searchwpgists/58980fa333c66e8113ca2f1ac68dffb5 to your computer and use it in GitHub Desktop.
Save searchwpgists/58980fa333c66e8113ca2f1ac68dffb5 to your computer and use it in GitHub Desktop.
Add bonus weight from Custom Field value in SearchWP
<?php
// Add bonus weight from Custom Field value in SearchWP.
// @link https://searchwp.com/documentation/knowledge-base/add-relevance-weight-date/
add_filter( 'searchwp\query\mods', function( $mods ) {
global $wpdb;
// Custom Field name. Needs to store data as YYYYMMDD (ACF does this already).
$my_meta_key = 'date_field';
$mod = new \SearchWP\Mod();
$mod->set_local_table( $wpdb->postmeta );
$mod->on( 'post_id', [ 'column' => 'id' ] );
$mod->on( 'meta_key', [ 'value' => $my_meta_key ] );
$mod->relevance( function( $runtime ) use ( $wpdb, $my_meta_key ) { return $wpdb->prepare( "
COALESCE( ROUND( ( (
UNIX_TIMESTAMP( {$runtime->get_local_table_alias()}.meta_value )
- (
SELECT UNIX_TIMESTAMP( meta_value )
FROM {$wpdb->postmeta}
WHERE meta_key = %s
ORDER BY meta_value ASC
LIMIT 1
)
) / 86400 ), 0 ), 0 )", $my_meta_key );
} );
$mods[] = $mod;
return $mods;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment