10

Is it possible to exclude some fields when using search?

Getting the q parameter from the URL and searching the products section including all fields:

{% set query = craft.request.getParam('q') %}
{% set results = craft.entries.section('products').search(query) %}

This searches all fields, included those for "related articles" and "related products". I need to exclude those from the search.

Some experiments

Works to exclude hits in relatedProducts but limits the fields being searched to the productName field:

craft.entries.section('products').search('productName:'~ query ~' -relatedProducts:'~ query)

Does not work - also returns the product with a related product matching the query:

craft.entries.section('products').search(query ~' -relatedProducts:'~ query)

and the same when trying to include several fields before excluding relatedProducts:

craft.entries.section('products').search('productName:'~ query ~' OR productDescription:'~ query ~' -relatedProducts:'~ query)

Also tried searching just in the relatedProducts, confirming that it returns only the product with a related entry matching the query:

craft.entries.section('products').search('relatedProducts:'~ query)

2 Answers2

5

You can now use the attribute parameter in your search options, to set the fields the search term should apply to (feature introduced with Craft 2.5).

Unfortunatelly it's currently only possible to set a single attribute, but what you can do is to use the Preparse plugin to add a field to your elements where you collect / concatenate search terms from all relevant fields, then search in this field only.

The settings for your searchTerms Preparse field:

{{ entry.title }}
{{ entry.body }}
{{ entry.keywords }}

The search parameter:

{% set searchParam = {
    query: query,
    attribute: 'searchTerms'
    subLeft: true,
    subRight: true,
} %}
carlcs
  • 36,220
  • 5
  • 62
  • 139
4

What about including only those fields you want to search:

craft.entries.section('products').search('productName:'~ query ~' OR productDescription:'~ query ~' OR productFoo:'~ query ~' OR productBar:'~ query)

Yep I know, it's not very nice (but hey, it was you who started listing them). What you could do to make this ugly thing of a search parameter more manageable is to add the conditions programmatically:

{% set searchFields = [
    'productName',
    'productDescription',
    'productFoo',
    'productBar',
] %}

{% set searchParam %}

    {% for searchField in searchFields %}
        {{- not loop.first ? 'OR' -}}
        {{- searchField ~ ':' ~ query -}}
    {% endfor %}

{% endset %}

{% set results = craft.entries.section('products').search(searchParam|trim) %}
carlcs
  • 36,220
  • 5
  • 62
  • 139