1

Is there a way to sort entries by a customSortOrderFunction in a plugin?

Like: craft.entries.section('somename').orderBy(myCustomSortOrderFunction)

Where myCustomSortOrderFunction returns some data from another table.

Any suggestion or article, etc. will be helpful.

Thanks.

1 Answer 1

1

It's not a good idea to express the sorting logic in PHP, since that requires loading all results and then running them through the sorting function. If you have 10,000 entries and need the first 20 (according to your sort function), you're still going to load 10,000 entries and then throw out 9,980 of them.

Instead, you need to specify the sorting logic in the entry query, so the database can return the results in the correct sort order, and only return the number of results you need.

The orderBy method can take multiple forms. You can specify a single field or multiple fields in array notation, as well as the sort order (ascending or descending) for every field.

If that is not enough, you can use an expression to specify a custom sort function in plain SQL. You can create an expression in Twig using the expression function:

{% set result = craft.entries()
    .section('somename')
    .orderBy(expression('your expression here'))
    .all()
%}

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.