5

Is it possible to put conditions on the ordering of a loop of entries?

I have two fields: title and alphaTitle. I want to order alphabetically, by alphaTitle if it has a value, otherwise by title. Title will always have a value but I only want to order by title if there is no alphaTitle. I've been having some trouble figuring out if this is possible or how to do it - any chance someone can point me in the right direction?

1 Answer 1

12

There are several ways you could attack this, but probably the easiest is directly from the SQL side with something like this using a SQL CASE statement:

{% set entries = craft.entries.section('news').order('(CASE WHEN field_alphaTitle IS NULL OR field_alphaTitle = "" THEN title ELSE field_AlphaTitle END)').find() %}

<ul>
    {% for entry in entries %}
        <li>TITLE = {{ entry.title }} / ALPHA TITLE = {{ entry.alphaTitle }}</li>
    {% endfor %}
</ul>

Note that is assuming that alphaTitle is a custom field and title is the standard one available to all entries.

3
  • beautiful, that worked!
    – Becky Soll
    Aug 25, 2014 at 19:24
  • Glad it did! Would you mind marking it as the answer?
    – Brad Bell
    Aug 25, 2014 at 19:34
  • @BeckySoll Please mark this answer as correct if it solved your problem. This gives credit to Brad. Apr 9, 2015 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.