How can I get the top level ancestor of an entry within a structure? I've tried:

{% set rootEntry = null %}
{% for ancestor in entry.getAncestors() %}
    {% set rootEntry = ancestor %}
{% endfor %}

But that only returns the most recent ancestor back and doesn't go all the way up the chain.

1 Answer 1


getAncestors() gets all entries that are ancestors. Since you're looping through them what rootEntry is set to last time through is the closest ancestor.

You can avoid the loop and just get the first one:

{% set rootEntry = entry.getAncestors().first() %}
  • on craft4 $entry->getAncestors()->level(1)->one()
    – tenshi
    Commented Jan 10 at 2:09

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.