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

Last updated December 18, 2018 « Knowledge Base

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 );
view raw functions.php hosted with ❤ by GitHub

Now that we’re JOINed 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) )";
} );
view raw functions.php hosted with ❤ by GitHub

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.

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