I have a section of "video" entries which are related to another section via an "area" field in the "video" section. When you do a search on the front end by area then the related video displays as expected. What I also have in the area section is a text field full of postcodes, what I would like to happen is when you then do a search by postcode then the video displays that is related to that area, is that possible?

Here is my code that works for searches by area:

{% set query = craft.request.getParam('search') %}
{% set searchEntries = craft.entries.search(query).order('score') %}

{% for entry in searchEntries.video(':notempty:') %}
  {% set video = entry.video %}
  {{ video.embed({ width: 340, height: 191, showinfo: false }) }}
{% endfor %}

Do another call to craft.entries when you loop through the "area" entries and include the section and relatedTo params:

{% for entry in searchEntries %}
    {% set videos = craft.entries.section('videoSectionHandle').relatedTo(entry) %}
    {% for video in videos %}
         {# Output video here #}
    {% endfor %}
{% endfor %}

If you're trying to maintain a one-to-one relationship it might make sense to limit the relation query to one result, and to include the first param to return the first (and only) result and not an array – then you can omit the nested for loop:

{% for entry in searchEntries %}
    {% set video = craft.entries.section('videoSectionHandle').relatedTo(entry).limit(1).first() %}
    {{ video ? #--Output video here--# }}
{% endfor %}

You can read more about the relatedTo param here, it's pretty powerful.

| improve this answer | |

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.