2

I'm looking how to use the .offset(x) parameters of craft.entries inside the ElementAPI.

I tried to add 'offset' => 1 before, after and inside the criteria array, but the x first entries are still added to the JSON.

How can I skip the first X entries of ElementAPI?

  • 1
    It seems that offset only works when pagination is set to false. – missmatsuko Feb 13 '19 at 22:32
2

We just released Element API 2.6.0 with added support for the offset criteria param, in combination with paginate => true.

(Thanks to @missmatsuko for posting a GitHub issue about it: https://github.com/craftcms/element-api/issues/99)

3

It seems that offset doesn't work when pagination is set to true (which is its default value).

If you don't need pagination for your results, you can add your offset in criteria and set pagination to false.

If you do need pagination and the desired offset is the same as elementsPerPage, you can get your results starting from page 2. You'll have to make sure you're actually getting page 2 because it will return page 1 if there aren't enough results for a second page.

If you do need pagination and the desired offset is different from elementsPerPage, you can try what I've done here.

'stories.json' => function() {
    // Get get IDs of the "offset" entries. Set `limit` to the offset amount you want.
    $excludedIds = Entry::find()
        ->section('stories')
        ->limit(4)
        ->ids();

    // Form value for id in criteria to exclude the above entries.
    $criteriaId = count($excludedIds) ? ('and, not ' . implode(', not ', $excludedIds)) : null;

    return [
        'elementType' => Entry::class,
        'criteria' => [
            'section' => 'stories',
            'id' => $criteriaId,
        ],
        'pretty' => true,
        'elementsPerPage' => 6,
        'transformer' => function(Entry $entry) {
            return [
                'title' => $entry->title,
                'url' => $entry->url,
                'id' => $entry->id,
            ];
        },
    ];
},

I found that you can still paginate results with a value for id set in criteria. So, I've excluded the IDs of the offset entries and paginated the results with those entries removed.

I've also made an issue on the Element API Github repo to see if there's a better solution: https://github.com/craftcms/element-api/issues/99

  • This answer might be for Craft 3. For Craft 2 use the following element query: $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->section = 'news'; $criteria->limit = 1; $excludedIds = $criteria->ids(); – biko Jul 20 '19 at 2:53

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.