Skip to main contentSkip to footer

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

WP Job Manager

Relevanssi doesn’t work with the WP Job Manager search. The solution is fortunately simple: you can just disable Relevanssi for the WP Job Manager page. To disable Relevanssi, add this to your site: add_action( ‘get_job_listings_init’, ‘relevanssi_fix_for_wp_job_manager’ ); function relevanssi_fix_for_wp_job_manager(){ remove_filter( ‘posts_request’, ‘relevanssi_prevent_default_request’ ); remove_filter( ‘the_posts’, ‘relevanssi_query’ ); } Thanks to…

Indexing custom post statuses
If you’re using custom post statuses, Relevanssi requires some tinkering. By default, Relevanssi only handles posts that are of status…

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