1

Currently collaborating on a site with another developer, which is using ElementAPI pretty heavily for content delivery.

Is there a way to limit the number of returns on any given json feed? Say; only return the 10 most recent entries in any given channel? Or order the returned data by a specified field asc/desc?

A sample code:

'trucks.json' => [
  'elementType' => 'Entry',
  'criteria' => ['section' => 'trucks'],
  'paginate' => false,
  'transformer' => function(EntryModel $entry) {
    return [
      (int)$entry->id,
      $entry->manufacturer,

2 Answers 2

2

This should do the trick:

'criteria' => [
    'section' => 'trucks',
    'limit'   => 10,
    'order'   => 'title asc',
]

The Element Criteria Model documentation has more information about setting criteria.

Update for Craft 3.x*

The “order” element query param has been deprecated. Use “orderBy” instead.

* Craft v3.0.11 reports this in the /admin under deprecation errors

3
  • Ah that did the trick. I tried that but not from WITHIN criteria, only after criteria.
    – Noah Yamen
    Commented Apr 19, 2017 at 19:00
  • Is there a means to change the sort via the api, versus doing it on the front-end?
    – Noah Yamen
    Commented Apr 19, 2017 at 19:01
  • Updated my answer with an "order" parameter. Commented Apr 19, 2017 at 19:05
3

Just setting the limit property doesn’t do the trick alone, you need to deactivate pagination, too:

'criteria' => [
    'section' => 'trucks',
    'limit'   => 10,
    'orderBy'   => 'title asc',
],
'paginate' => false,

Your Answer

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

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