Learn how to adjust relevance scores for certain products based on current search query terms.
In this guide, we will learn how to increase the relevance score of specific products based on the current search query.
Example:
If the search query contains the words hoodie or jacket, we want products with IDs 1, 2, 3 to appear at the top of the search results.
This can be achieved using the following code snippet:
class AWS_Score_By_Product { public $search_terms = array(); public $search_for = array( 'hoodie', 'jacket' ); public $products = array( 1, 2, 3 ); public $relation = 'equal'; // equal, not equal, contains, not contains function __construct() { add_filter( 'aws_search_terms', array( $this, 'aws_search_terms' ) ); add_filter( 'aws_search_query_array', array( $this, 'aws_search_query_array' ) ); } function aws_search_terms( $search_terms ) { $this->search_terms = $search_terms; return $search_terms; } function aws_search_query_array( $query ) { $has_term = false; if ( $this->search_terms ) { foreach ( $this->search_terms as $term ) { switch ( $this->relation ) { case 'equal': if ( in_array( $term, $this->search_for ) ) { $has_term = true; } break; case 'not equal': $temp = true; foreach ( $this->search_for as $sterm ) { if ( $term === $sterm ) { $temp = false; } } if ( $temp ) { $has_term = true; } break; case 'contains': foreach ( $this->search_for as $sterm ) { if ( strpos( $term, $sterm ) !== false ) { $has_term = true; } } break; case 'not contains': $temp = true; foreach ( $this->search_for as $sterm ) { if ( strpos( $term, $sterm ) !== false ) { $temp = false; } } if ( $temp ) { $has_term = true; } break; } } } if ( $has_term ) { error_log('add'); $relevance = sprintf( "( case when ID IN ( %s ) then 800 else 0 end ) + ", implode( ',', $this->products ) ); $query['relevance'] = preg_replace( '/(SUM([sS]*?([sS]*?case[sS]*?end[sS]*?)[sS]*?+/i', '$0' . $relevance, $query['relevance'] ); } return $query; } } new AWS_Score_By_Product();
Customizable Parameters
$search_for
- An array of search query words that must match the current query.
$product_ids
- An array of product IDs to boost in the search results.
$relation
- Defines how the search query is evaluated:
equal
- Boost relevance if the search query contains exact words from $search_for
.
not equal
- Boost relevance if the search query does not contain any words from $search_for
.
contains
- Boost relevance if the search query contains part of any word from $search_for
.
not contains
- Boost relevance if the search query does not contain any part of the words from $search_for
.