Last active
April 14, 2021 15:36
-
-
Save jchristopher/d17a18f0a31e676dfa65fc27348f6010 to your computer and use it in GitHub Desktop.
Add bonus weight from Custom Field value in SearchWP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Add bonus weight from Custom Field value in SearchWP. | |
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