1

I'm trying to create somewhat of a clever search for which only searches through certain pages of my site. At the moment, it can search those pages, but instead of the result returning the page name, I want it to return a field within the matrix field which the search query can be found in.

As an example below, if a user were to search for Lorem Ipsum, I want it to return the page name as well as the matrix field title.

This is my title

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

Desired result:

Page Name: This is my title

So far, the code I have can be found here, but I'm unsure how to access to exact matrix field title and add it to the query.

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).order('score').section(['pageOne', 'pageTwo', 'pageThree']) %}

{% if entries|length %}
    {% for entry in entries %}
        <a href="{{ entry.url }}">{{ entry.title }}</a>
    {% endfor %}
{% endif %}

Is this possible to achieve?

1 Answer 1

2

I assume, that title is a subfield of a matrix field, because title is a reserved name in craft. So as far as I understand your Question, you want to get some results out of a matrix field thats in one of your pages ('pageOne', 'pageTwo', 'pageThree'). That means you have to loop over this field as well.

{% if entries|length %}
   {% for entry in entries %}
       {% for block in entry.matrixFieldHandle %}
          <a href="{{ entry.url }}">{{ entry.title }} - {{ block.matrixTitle }}</a>
       {% endfor %}
   {% endfor %}
{% endif %}
5
  • Perfect! Thank you
    – Amy
    Commented Feb 8, 2018 at 9:49
  • Your Welcome. I just realized, that title is also forbidden inside a matrix field, so i changed the handle inside the block to 'pageName' ;)
    – Laslo89
    Commented Feb 8, 2018 at 9:51
  • What you had was perfect, {{ block.title }} was what gave me the field title. just needed both {{ entry.title }} - {{ block.title }} for page name and field name :)
    – Amy
    Commented Feb 8, 2018 at 9:52
  • @Amy I'm just curious: how were you able to insert title as a field handle in your craft matrix field? title is a reserved keyword it's usually not possible to use it as a handle Commented Feb 8, 2018 at 10:28
  • The section I was looking to search through was a Q&A section, so my title was {{ entry.question }}. You are right, you cannot use just 'title', bad example on my part
    – Amy
    Commented Feb 8, 2018 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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