TL:DR; How do I add a custom sorting to Craft?

I am currently building a system which is very tag-centric. I am rebuilding my side project in CraftCMS (https://email.subscribeto.at/) which was custom PHP as a prototype.

Entries are tagged with one or more categories, then on the front-end the user can search for categories and the results are returned.

Currently, the results can be sorted by "relevance" which I would like to replicate on CraftCMS.

I tried to use .search() as it has a score, however this score is not what I want as it is not additive. I want to search with OR but for the score to be additive.

For example, if I have 2 entries, one with tags "a" and on with "a, b" and I search for "a, b", the first one has a score of 50 (as 100% of it's tags match 50% of the search) and the second a score of 17 (not sure how it gets this, would expect 100%)

Also, .search seems a bit fragile when I could us relatedTo().

I have a local module installed for some overrides already, so my question is:

How would I add a custom property to each entry and then order by that?

Thanks in advance for your help

1 Answer 1


You can add custom properties to elements using behaviors. In this case you want to add your 'getSearchScore()' logic.

Here's a good article on how behaviors work in Craft CMS and a current PR on the documentation to have behaviors information added.

  • Thanks! I've been able to now add the behaviour, I am struggling to order by that behaviour when returning the entries May 15, 2020 at 18:07

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.