Skip to content

Instantly share code, notes, and snippets.

@sjelfull
Created October 4, 2015 01:42
Show Gist options
  • Save sjelfull/49a895363c303b94ae42 to your computer and use it in GitHub Desktop.
Save sjelfull/49a895363c303b94ae42 to your computer and use it in GitHub Desktop.
Method for widening user search to include more results (show matches of only one word even if multiple are provided, and matching parts of words). Probably not a good idea for high traffic sites, but a blessing for standard ones.
{# Instead of using standard search, like that: #}
{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).order('score') %}
{# We can expand it to be more intuitive to the user and give better results: #}
{% set query = craft.request.getParam('q') %}
{# expand query by widening match from `xxx` to `*xxx*`, and `xxx yyy` to `*xxx* *yyy*`, etc #}
{% set expanded_query = query
| replace('/ {2,}/', ' ')
| replace('/(^[^*])/', '*$1')
| replace('/(?<= )([^*])/', '*$1')
| replace('/([^*]$)/', '$1*')
| replace('/([^*])(?= )/', '$1*')
%}
{# switch AND to OR, to have partial match results #}
{% set expanded_query = expanded_query
| replace(' ', ' OR ') %}
{% set entries = craft.entries.search(expanded_query).order('score') %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment