Skip to main contentSkip to footer

Partial matches to just one custom field

Is it possible to set (with filters and/or actions/functions) Relevanssi to use whole words keyword matching for post titles and 2 custom fields, and partial keyword matching only for a specific custom field (sku in this case)?

Indeed it is! That is, you can’t set different keyword matching methods to different parts of the post, but you can enable partial matching and then discard partial matches for the parts where they are not wanted.

To allow partial matches, but only in the custom field sku, you can do this with relevanssi_match:

add_filter( 'relevanssi_match', 'rlv_partial_partial', 10, 3 );

/**
 * Allows partial matches but only in the custom field 'sku'.
 *
 * For posts that have partial matches outside the custom field 'sku',
 * set the weight to 0 to eliminate them from the search results.
 *
 * @param object $match The match object with the custom field detail.
 * @param int    $idf   The IDF value for calculating weight, not used.
 * @param string $term  The search term.
 *
 * @return object $match The modified match object.
 */
function rlv_partial_partial( $match, $idf, $term ) {
	if ( $term !== $match->term ) {
		$cf_detail = json_decode( $match->customfield_detail );
		if ( ! isset( $cf_detail->sku ) ) {
			$match->weight = 0;
		}
	}
	return $match;
}

This requires Relevanssi Premium, because in the free version the customfield_detail field is not included in the $match object. (It’s possible to replicate the functionality by checking the sku custom field with get_post_meta( $match->doc, 'sku', true ); but that adds a lot of database queries and makes the search perform worse).

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

EmbedPress autoembeds
EmbedPress has an auto-embed feature that tries to embed all URLs found in posts. This can cause problems with Relevanssi:…
Integrating Post Views Counter stats

…in the weight calculations is straightforward. The best tool to use is the relevanssi_results filter hook. It lets us modify the weights of the posts. For each post, we calculate a weight multiplier based on the visitor stats and then multiple the weight of the post with that. I add…

German umlauts
By default, the search ignores German umlauts. Searching for “uber” will also find “über” and so on. This ignorance is…

Related Posts:

Comment Section:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed