Sorting Entries Numerically by Custom Field in Movable Type

| No Comments | No TrackBacks |
For some time now you can sort entriesin Movable Type by the value of one of their custom fields, which is really neat and allows you to create your own arbitrary orderings.  However, the sorting always happens alphabetically, which means that '100' ends up before '11'.  How to fix this?
The simple solution

Zero-pad all numbers you put in a custom field that you intend to sort by: 001, 010, 100... will line up perfectly.  Drawbacks are that you need to type a lot of extra zeroes and you better make sure you use enough places or you will end up with 1000 coming before 110...

The template solution

Compare the output of the first and last bit of template code in this example:

<mt:entries sort_by="field:order" sort_order="descend">
<li><mt:entrytitle> <mt:entrydataorder></li>
<mt:setvarblock name="thetitle"><mt:entrytitle></mt:setvarblock>
<mt:setvarblock name="thelist{$thetitle}"><mt:entrydataorder></mt:setvarblock>


<mt:loop name="thelist" sort_by="value numeric reverse">
<li><mt:var name="__key__"> <mt:var name="__value__">

For three entries, titled 'One', 'Eleven' and 'Hundred' and with respectively 1, 11 and 100 in the 'EntryDataOrder custom field, the result is this:

  • Eleven - 11
  • Hundred - 100
  • One - 1

  • Hundred - 100
  • Eleven - 11
  • One - 1

  • The code makes use of the fact that the mt:entries tag does not have an option to force numeric sorting, but mt:loop does.  By storing the entry titles and custom field values in a hash array and then sorting it on the 'value' but numerically we get the desired output.

    No TrackBacks

    TrackBack URL:

    Leave a comment