Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active September 18, 2020 00:36
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 jchristopher/a066dfafda6393d034e5374fb47f0f8a to your computer and use it in GitHub Desktop.
Save jchristopher/a066dfafda6393d034e5374fb47f0f8a to your computer and use it in GitHub Desktop.
Tell SearchWP to give more weight to WP_Posts with more comments
<?php
// Add relevance weight based on number of comments.
add_filter( 'searchwp\query\mods', function( $mods ) {
global $wpdb;
// Multiply the number of comments by this multiplier.
$comment_count_multiplier = 1;
$mod = new \SearchWP\Mod();
$mod->set_local_table( $wpdb->posts );
$mod->on( 'ID', [ 'column' => 'id' ] );
$mod->weight( function( $runtime_mod ) use ( $comment_count_multiplier ) {
$local_alias = $runtime_mod->get_local_table_alias();
return "(IF({$local_alias}.comment_count > 0,
(CASE
WHEN (LOG({$local_alias}.comment_count) > 6) THEN 6
WHEN (LOG({$local_alias}.comment_count) < 1) THEN 1
ELSE ROUND(LOG({$local_alias}.comment_count))
END),0))";
} );
$mods[] = $mod;
return $mods;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment