Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add bonus weight from Custom Field value in SearchWP
<?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->weight( 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
You can’t perform that action at this time.