Created
October 4, 2015 01:42
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {# 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