3

I have a search page. I can search either categories or entries using

{% set entries = craft.entries.search(query).order('score') %}
{% set categories = craft.categories.search(query).order('score') %}

I have added quite a bit of content in each category i.e. what it's all about etc. and I would like this content returned like a standard search result going to the category URL (it works when I search categories only)

I've tried to merge the above two arrays

{% set results = categories | merge (entries) %}

But that's obviously not how you do it because it throws a craft error.

Now, I guess I could return the results of one, and then the other, but I was hoping to have the score create a more sensible order of relevant results.

  • My workaround (so not an answer), it put all the content for each category into a matching structure section, which in turn has the category as a field. So when this structure entry is found in the search, it in turn redirects the category field URL, in effect getting around the problem. It just means that when I add a category I have to go and add a matching entry. – Jack McKenzie Apr 4 '15 at 6:36
5

The reason you're getting an error when trying to merge the two search results is that they are not technically arrays, but elementCriteriaModels. To convert them to actual arrays you would need to use the find() method.

{% set entries = craft.entries.search(query).order('score').find() %}
{% set categories = craft.categories.search(query).order('score').find() %}
{% set results = categories|merge(entries) %}

The problem with this is that the sort order will be wrong (showing all categories and then all entries). Although you could potentially sort the results array using something like the supersort plugin.

The other option to consider is redesigning the database so that there is nothing in categories that needed to be searched for, which might simplify things in the end.

  • I don't think you have access to score from the template, so sorting the merged array is not possible. – carlcs Apr 5 '15 at 19:55
  • Thanks. So in the end I added the content I wanted searched into a Structure that matches the Category set up, and matched them accordingly both for display on a page, and a redirect from the search result. – Jack McKenzie Apr 6 '15 at 23:06
  • @Douglas there's a FR to expose the score to the templates. – carlcs Apr 14 '15 at 12:10

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.