SearchWP

Version 4 Documentation

Force exact matches for multiple words

SearchWP’s support for quoted/phrase searching produces results that match the submitted multi-word search exactly. By default, this requires that the visitor wrap the exact match string in double quotes as is the common practice in other search engines.

If you would like to force exact match logic to happen for all multi-word searches, we can use the following hook:

Note: you must tick the checkbox to enable quoted search support on the Advanced tab of the SearchWP settings screen.

All hooks should be added to your custom SearchWP Customizations Plugin.

<?php
// Force multiple word searches to use quoted search logic if quotes are not added.
// NOTE: Quoted search must be enabled (checkbox on the Advanced tab)
add_filter( 'searchwp\query\search_string', function( $search_string, $query ) {
// If there are already quotes, bail out.
if ( false !== strpos( $search_string, '"' ) ) {
return $search_string;
}
// If there's only one word, bail out.
if ( false === strpos( $search_string, ' ') ) {
return $search_string;
}
return '"' . $search_string . '"';
}, 30, 2 );

With this hook in place all multiple word searches will get wrapped in double quotes, producing results as though the original search was wrapped in double quotes.