Join us in Montréal on September 18-20 for Dot All 2019, the official Craft developer conference!

Enabling Fuzzy Search by Default

By default, Craft’s search feature requires you to begin/end each keyword with an asterisk (*) if you want it to be treated as “fuzzy”, so even partial matches of the keyword will be included in the search results.

As of Craft 2.5, it is possible to enable fuzzy searching by default, so users don’t have to worry about typing those asterisks. You can enable it at a global level, which will affect all search params as well as search bars within the Control Panel, or you can enable it for each individual search parameter where it makes sense.

To enable fuzzy searching on a global level, open up craft/config/general.php and set the defaultSearchTermOptions to the following:

'defaultSearchTermOptions' => array(
    'subLeft' => true,
    'subRight' => true,

The subLeft key allows search terms to match keywords that have additional characters before the term; and the subRight key allows search terms to match keywords that have additional characters after the term. (You can remove one of those keys if you don’t want it.)

To enable fuzzy searching on a per-search param basis, set your search param value to an object rather than a search query string:

{% set results = craft.entries({
    section: 'news',
    search: {
        query: craft.request.getQuery('q'),
        subLeft: true,
        subRight: true                
}) %}

If you go this route, note that the query property is required. Beyond that, all of the same keys available to the defaultSearchTermOptions config setting can also be used here – not just subLeft and subRight.