こんにちは。MT大好き丸山です。
今回はカスタムフィールドの値による並び替え処理について書いておきます。
mt:Entriesでカスタムフィールドの値を元に並び替えをしたい時、
sort_by="field:customfieldbasename"
という指定をすることでカスタムフィールドの値で並び替えが可能ですが、カスタムフィールドの値は文字列として並び替えられてしまうため、例えば「商品の値段順にしたい」といった場合などに理想の結果が得られません。
例:cf_priceというカスタムフィールドに値段が入っている場合。
<mt:Entries sort_by="field:cf_price" sort_order="ascend">
<mt:EntriesHeader>
<table>
</mt:EntriesHeader>
<tr>
<th><$mt:EntryTitle$></th>
<td><$mt:cf_price$>円</td>
</tr>
<mt:EntriesFooter>
</table>
</mt:EntriesFooter>
</mt:Entries>
出力結果
この問題を解決するために、出力したい内容を一度ハッシュへ入れてから並び替えをします。
<mt:Entries>
<mt:SetVarBlock name="title"><$mt:EntryTitle$></mt:SetVarBlock>
<mt:SetVarBlock name="entries{$title}"><$mt:cf_price$></mt:SetVarBlock>
</mt:Entries>
<mt:Loop name="entries" sort_by="value numeric">
<mt:If name="__first__">
<table>
</mt:If>
<tr>
<th><$mt:Var name="__key__"$></th>
<td><$mt:Var name="__value__"$>円</td>
</tr>
<mt:If name="__last__">
</table>
</mt:If>
</mt:Loop>
出力結果
sort_byに指定されているnumericがポイントで、この指定があると値を数値として処理してくれます。
sort_by="value numeric"
更にreverseを指定すると昇順・降順の入れ替えもカンタンです。
...もう何も恐くない><