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 a couple of SearchWP hooks we can make that happen!
The first thing we need to do is JOIN
SearchWP’s query with WordPress’ term relationships table. This is easily done using theĀ searchwp_query_join
hook:
<?php | |
add_filter( 'searchwp_query_join', function( $sql, $post_type, $engine ) { | |
global $wpdb; | |
return "LEFT JOIN {$wpdb->prefix}term_relationships as swp_tax_rel ON swp_tax_rel.object_id = {$wpdb->prefix}posts.ID"; | |
}, 10, 3 ); |
Now that we’re JOIN
ed with WordPress’ term relationships table, we can conditionally add arbitrary weight to entries that have been given a specific term. In this case we’re going to add a weight of 1000
to any results that have been given a term with an ID of
7
.
I’m using a weight of 1000
because I want to ensure that these entries bubble to the top of my search results page. We can use the searchwp_weight_mods
hook to apply this logic:
<?php | |
add_filter( 'searchwp_weight_mods', function( $sql ) { | |
$category_id_with_bonus = 7; | |
$additional_weight_for_category = 1000; | |
// If an entry is in Category ID 7, give it an additional weight of 1000 | |
return $sql . " + ( IF ((swp_tax_rel.term_taxonomy_id = {$category_id_with_bonus}), {$additional_weight_for_category}, 0) )"; | |
} ); |
And we’re done! Any results that have been given term 7
will automatically inherit a bonus weight of 1000, effectively bumping those entries to the top of the results.