Posted on

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).

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

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