I originally asked this on Stack Overflow, but I'm hoping for more response here.

In Craft, I'm trying to order entries by the title. Each title is a number, but the sort function handles it like a string. Because of that 100 shows up before 2, 31 before 4, and so on.

{% for entry in craft.entries.section('mySection').order('title').find() %}
{% endfor %}

Is there a way to do this without extending twig?

  • I see that you've ask this question before, over on main stackoverflow. Did you try the answer there using natsort? Question with natsort answer – Nicolaides Jun 12 '14 at 13:55
  • Yes, as mentioned in my question I originally asked this on stack overflow. I would like to know is if there is a way to do this without extending twig. – Spoeken Jun 12 '14 at 13:59

You can do that using MySQL’s cast() function:

craft.entries.section('mySection').order('cast(title as unsigned)')

Alternatively, you might get better performance if you create an actual Number field called “numberTitle”, attach it to your Entry Type, and set the Entry Type’s title to be dynamically generated using the template “{numberTitle}”. Then you can just order by that field instead:

  • That 2nd technique is interesting, but where exactly do you set that template for the title field? Can I set templates for other fields too? – carlcs Jun 12 '14 at 15:04
  • 2
    See buildwithcraft.com/docs/… – Brandon Kelly Jun 12 '14 at 15:07
  • Amazing answer. Just watch out if you're ordering by a custom field you need to put field_ in front of the field handle. Eg: craft.entries().section('mySection').orderBy('cast(field_customFieldHandle as unsigned)') (Also use orderBy instead of order in Craft 3) – Brimby Oct 28 '20 at 22:24

Twig doesn't have a natsort() filter.

But I've put together a simple plugin which extends the sort-filter:


This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .