I have a plugin which contains a Record. My record contains a foreign key of the related element ID. The only other column in my custom table is the value I'd like to sort by.

In Twig syntax, how can I expand on a normal Craft query to sort by a column in my custom table?

Ordinary query:


Ordinary query which sorts by my custom data:



I've done something similar to this once before... But in that case, I used the modifyElementsQuery method in my Field Type. Since this new plugin doesn't require a field type, I'm not exactly sure of the best way to modify a standard query.

1 Answer 1


You can't do this using the craft.entries tag in twig. You'll need to create a new function in your plugin that returns the entries in your custom order.

Assuming you can create an array of element ids in your custom order then the following code should allow you to then fetch entries in that order:

$criteria = craft()->elements->getCriteria(ElementType::Entry);

// filter entries by element ids
$criteria->setAttribute('id', $elementIds);

// order entries by element ids
$criteria->setAttribute('order', 'FIELD(elements.id, '.join(', ', $elementIds).')');

// get entries
$entries = craft()->elements->findElements($criteria);
  • Thanks Ben! I'm not sure if this is exactly what I'm looking for (although it sounds like what I'm looking for might not exist). I'm gonna try a few things based on your example, I'll let you know how it goes.
    – Lindsey D
    Sep 26, 2014 at 5:36
  • Ok, it looks like this is going to work well! I made a few tweaks (too much to explain here), but the core ideas came from this suggestion. Thanks Ben!
    – Lindsey D
    Sep 26, 2014 at 8:43
  • good to hear. as is often the case with craft, there are many ways of achieving this based on your specific needs. this seemed like the cleanest to me.
    – Ben Croker
    Sep 26, 2014 at 10:37
  • Hey Ben, as you said "there are many ways of achieving this"... I just discovered this method which also worked great for me! It actually saved me a separate query, so I didn't have to figure out $elementIds separately.
    – Lindsey D
    Sep 27, 2014 at 21:27
  • very nice solution!!
    – Ben Croker
    Sep 28, 2014 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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