<p><a href="http://buildwithcraft.com/docs/templating/entrymodel#getAncestors"><code>getAncestors()</code></a> gets all entries that are ancestors. Since you're looping through them what rootEntry is set to last time through is the closest ancestor.</p>

<p>You can avoid the loop and just get the first one:</p>

<pre><code>{% set rootEntry = entry.getAncestors().first() %}
</code></pre>

CC BY-SA 4.0
2024-01-10T02:09:04.913Z
on craft4 `$entry->getAncestors()->level(1)->one()`
tenshi
CC BY-SA 3.0
2014-08-27T01:21:02.370Z
2014-08-27T01:21:02.370Z
Simon Kuran
<p>How can I get the top level ancestor of an entry within a structure? I've tried:</p>

<pre><code>{% set rootEntry = null %}
{% for ancestor in entry.getAncestors() %}
    {% set rootEntry = ancestor %}
{% endfor %}
</code></pre>

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

<structure>
Get structure top ancestor
# Get structure top ancestor

(Asked by: username_0 on 2014-08-26)

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.

**Tags:** structure


---

## 1 answers

### Answer by username_1 on 2014-08-27. Score: 7

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() %}

> **Comments:**
> **username_2**: on craft4 `$entry->getAncestors()->level(1)->one()`  

---

