Posted on

Forced phrase search with fallback

Relevanssi by default does not consider the search query a phrase, or value posts where the words in the search query appear together. Sometimes people do expect that, especially in AND searches. Relevanssi however does not have the information about the nearby words, so it’s not possible for Relevanssi to factor that in.

Relevanssi does support the sentence parameter in WordPress, which makes all searches phrase searches. It’s easy to enable:

add_filter( 'relevanssi_modify_wp_query', 'rlv_force_sentence' );
/**
 * Enables the `sentence` parameter in Releavnssi queries.
 *
 * @param WP_Query $query The query object.
 *
 * @return WP_Query The modified query object.
 */
function rlv_force_sentence( $query ) {
  $query->set( 'sentence', true );
  return $query;
}

This makes all queries automatically phrase searches. Of course, that has a huge drawback of causing large amount of searches that don’t match a phrase find nothing.

In Relevanssi, you can run a fallback search. If nothing is found, the fallback is triggered with the relevanssi_fallback filter hook, and it’s possible to adjust the search parameters to disable the sentence parameter then:

add_filter( 'relevanssi_fallback', 'rlv_phrase_fallback' );
/**
 * Triggers a fallback search when nothing is found.
 *
 * @param array $args The search arguments in the index 'args'.
 *
 * @return array The search arguments, with the results from
 * relevanssi_search() in 'return'.
 */
function rlv_phrase_fallback( $args ) {
  $args['args']['sentence'] = false;
    
  // Disable this filter to avoid an infinite loop.
  remove_filter( 'relevanssi_fallback', 'rlv_phrase_fallback' );
  
  // Run a search with the modified arguments.
  $return = relevanssi_search( $args['args'] );
  
  // Re-enable the filter.
  add_filter( 'relevanssi_fallback', 'rlv_phrase_fallback' );
    
  $args['return'] = $return;
  return $args;
}

Now all searches are first phrase searches, then if nothing is found the fallback is triggered, the sentence parameter is disabled and the search is run again with the same arguments.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.