3

I want to link to enabled sibling entries within a structure and am struggling to get it working.

This is what my structure looks like:

Because I only want to fetch entries that are enabled, I followed the docs instructions and fetch previous entries like this:

{% set prevEntry = craft.entries.positionedBefore(entry).order('lft desc').first() %}

With this, when on the Prince Phillip entry, I thought that would return null for prevEntry, but it is returning the Altynia Asylmoratova entry.

How can I fetch previous and next entries that are direct siblings and enabled?

1 Answer 1

7

After trying a few more things, I realised I needed the descendantOf parameter to get this working.

This is what my code looks like:

{% set prevEntry = craft.entries.descendantOf(entry.parent).positionedBefore(entry).order('lft desc').first() %}
{% if prevEntry is null %}
  {% set prevEntry = entry.siblings.last() %}
{% endif %}

{% set nextEntry = craft.entries.descendantOf(entry.parent).positionedAfter(entry).first() %}
{% if nextEntry is null %}
  {% set nextEntry = entry.siblings.first() %}
{% endif %}

This restricts the positionedBefore and positionedAfter parameters to only work with entries that have the same parent as the current entry.

If there is no previous or next entry, I link to the first or last sibling entry instead, creating a loop.

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.