I have the following text search input field:

<form action="{{ url('search') }}">
    <input type="search" name="q" placeholder="Search">

I would like to search each keyword in the user's query with the OR logic as per Craft docs.

salty OR dog containing either “salty” or “dog” (or both).

How can I separate the user's text search for "salty dog" so that the search query returns results for "salty" or "dog" instead of only for results containing "salty dog"?

Below is how I currently have the search set up in the template:

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search('*' ~ query ~ '*').order('score') %}
{% paginate craft.entries.search('*' ~ query ~ '*').limit(10).order('score') as pageInfo, pageEntries %}

I have fuzzy search enabled via config:

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

One way to do it is to split the search query on spaces, and then join it with 'OR':

{% set query = craft.request.getParam('q')|split(' ')|join(' OR ') %}
{% set entries = craft.entries.search(query).order('score') %}

The above will convert the search term "salty dog" to "salty OR dog". It'll work regardless of the number of keywords in the original search query string.

You should probably also make sure that you remove redundant whitespace from the original query, if you don't then a search query like "salty dog" (double space) will result in a query like "salty OR OR dog". Here's how you could do that using some regex and the replace filter:

{% set query = craft.request.getParam('q')|replace('/(( )+|(\\n)+)/', ' ')|split(' ')|join(' OR ') %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.