Last active
April 1, 2021 19:10
-
-
Save jchristopher/08bcd26e0f51a36ca82bc05ac0082e46 to your computer and use it in GitHub Desktop.
Arbitrary SearchWP weight multiplier on date as Custom Field value
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 | |
// Modify SearchWP calculated relevance using multiplier. | |
// @link https://searchwp.com/documentation/knowledge-base/add-relevance-weight-date/ | |
class My_SearchWP_Date_Modifier { | |
private $post_type = 'post'; | |
private $meta_key = 'event_date'; | |
private $modifier_past = 0.5; | |
private $modifier_future = 1.5; | |
private $alias = 'myswpdm'; | |
function __construct() { | |
global $wpdb; | |
// Modify SearchWP calculated relevance using multiplier. | |
add_filter( 'searchwp\query', function( $query, $args ) use ( $wpdb ) { | |
// Calculate a CUSTOM relevance. | |
$query['select'][] = "( SUM(relevance) * {$this->alias}mod ) AS {$this->alias}rel"; | |
// Implement a custom weight modifier based on date stored as meta value. | |
$query['from']['select'][] = " | |
( | |
CASE | |
WHEN UNIX_TIMESTAMP( {$this->alias}m.meta_value ) < UNIX_TIMESTAMP( NOW() ) | |
THEN {$this->modifier_past} | |
WHEN UNIX_TIMESTAMP( {$this->alias}m.meta_value ) > UNIX_TIMESTAMP( NOW() ) | |
THEN {$this->modifier_future} | |
ELSE 1 | |
END | |
) AS {$this->alias}mod | |
"; | |
// Custom JOINs. | |
$query['from']['from'][] = " | |
LEFT JOIN {$wpdb->posts} {$this->alias}p | |
ON ( {$this->alias}p.ID = {$args['index_alias']}.id | |
AND {$this->alias}p.post_type = '{$this->post_type}' ) | |
"; | |
$query['from']['from'][] = " | |
LEFT JOIN {$wpdb->postmeta} {$this->alias}m | |
ON ( {$this->alias}m.post_id = {$this->alias}p.ID | |
AND {$this->alias}m.meta_key = '{$this->meta_key}' ) | |
"; | |
// Use our custom relevance to sort results by overriding the default ORDERBY. | |
$query['order_by'] = [ "{$this->alias}rel DESC", ]; | |
return $query; | |
}, 20, 2 ); | |
} | |
} | |
new My_SearchWP_Date_Modifier(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment