Answers.Body: <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>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-01-10T02:09:04.913Z
Answers.Text: on craft4 `$entry->getAncestors()->level(1)->one()`
Answers.UserDisplayName: tenshi
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-08-27T01:21:02.370Z
Answers.LastActivityDate: 2014-08-27T01:21:02.370Z
Answers.UserDisplayName: Simon Kuran
Body: <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>
  
Tags: <structure>
Title: Get structure top ancestor
ThreadText: # 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()`](http://buildwithcraft.com/docs/templating/entrymodel#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()`  
  
  ---
  
  