1

For a given structure entry, I need to return the previous three, and the next three entries as one array. But if the given entry is the last in the structure, I need the "next three" to wrap around and select the first three entries, if that makes sense.

The given structure entry should not be included the results.

Does anyone know how I can achive this: all my efforts so far have failed or are far too complex.

0
1

Assuming that when you are on the first page, you don't show the last 3 entries of your structure and the single array you need is an array of entries, this should do it for you:

{# Set how many entries to have around current entry #}
{% set surroundingEntries = 3 %}

{# Fetch prev 3 entries - reverse order because of limit() #}
{% set prevEntries = craft.entries.positionedBefore(entry).orderBy('lft desc').limit(surroundingEntries).all() %}

{# Fetch next 3 entries #}
{% set nextEntries = craft.entries.positionedAfter(entry).limit(surroundingEntries).all() %}

{# if there aren't enough nextEntries, add some #}
{% if nextEntries|length < surroundingEntries %}
    {% set limit = surroundingEntries - nextEntries|length %}
    {% set extraEntries = craft.entries.section('sectionName').limit(limit).all() %}
    {% set nextEntries = nextEntries|merge(extraEntries) %}
{% endif %}

{# Put prevEntries back in order and merge nextEntries to it #}
{% set results = prevEntries | reverse | merge(nextEntries) %}

If you need an array of ids, replace .all() with .ids() and if I misunderstood you and you need two separate arrays, simply don't merge them as results and use nextEntries / prevEntries but don't forget to |reverse your prevEntries to get them back in order :)

2
  • I couldn't get this to work for my specific example but is almost certainly how someone else might do it, so have marked it as the right answer :-) – Daniel Feb 20 '19 at 17:54
  • @Daniel what's not right for your case? – Oli Feb 20 '19 at 18:08

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.