Add Weight to Entries (posts) within a Specific Category (taxonomy term)

By default SearchWP considers the actual content of taxonomy terms when performing searches. Depending on the way you’ve set up your site, you may want to give extra weight to entries regardless of taxonomy term, but instead add the weight to all entries that have been given a specific taxonomy term.

Using the searchwp_weight_mods hook we can make that happen!

function my_searchwp_weight_mods( $sql ) {
global $wpdb;
$swp_db_prefix = $wpdb->prefix . SEARCHWP_DBPREFIX;
// These are the taxonomy terms we want to give bonus weight.
$bonuses = array(
'term_id' => 17, // The taxonomy term ID to give the bonus weight.
'bonus_weight' => 1000, // The bonus weight to give this taxonomy term.
'term_id' => 88, // The taxonomy term ID to give the bonus weight.
'bonus_weight' => 300, // The bonus weight to give this taxonomy term.
foreach ( $bonuses as $bonus ) {
$sql .= " + ( IF ((
SELECT {$wpdb->prefix}posts.ID
FROM {$wpdb->prefix}posts
LEFT JOIN {$wpdb->prefix}term_relationships ON (
{$wpdb->prefix}posts.ID = {$wpdb->prefix}term_relationships.object_id
WHERE {$wpdb->prefix}posts.ID = {$swp_db_prefix}index.post_id
AND {$wpdb->prefix}term_relationships.term_taxonomy_id = {$bonus['term_id']}
) > 0, {$bonus['bonus_weight']}, 0 )) ";
return $sql;
add_filter( 'searchwp_weight_mods', 'my_searchwp_weight_mods', 20 );
view raw functions.php hosted with ❤ by GitHub

In reviewing the code please note that we’re giving weight to multiple taxonomy terms based on their ID. These taxonomy terms can be Categories, Tags, or any other registered taxonomy. You can retrieve the taxonomy term_id by reviewing the URL when editing the term in the WordPress administration area.

Alongside the term ID is a bonus_weight which can be customized for each taxonomy term, as you may want to give certain taxonomy terms precedence over others.

The rest of the snippet is responsible for translating those term_id/bonus_weight pairs into what’s necessary to modify SearchWP’s weight calculation based on those bonuses.

There is no need to rebuild your index after using this hook, the weight calculation happens in real time even as you add or remove these bonus-giving taxonomy terms from entries.

Fix Search on Your Site. No Coding Required!

Now you can utilize all of the content that's gone unrecognized by native WordPress search instantly with SearchWP

Get SearchWP