WordPress: How to fetch ancestors of current page?

2012-07-19 WordPress

If structure of you WordPress pages is very nested, you may want to get all identifiers that are parents (grand parents, grand grand parents etc.) of the current page. In this artcle I will show you how to achieve that just by using built-in WordPress function:


As the param we will use current page ID:


Now, we will assign the result into variable:

$parents = get_post_ancestors($post->ID);

Now variable parents is an array, that holds identifiers of all parent pages. If we just want to get the oldest one, lets combine it with PHP function called end(), that will return only last element of the given array. Because of the fact that get_post_ancestors returns identifiers in order from youngest to oldest, thanks to that we know that last element will be also the oldest one:

$oldest = end($parents);

Check the sample tree of nested articles:

  • Earth (4)
    • Europe (10)
      • Poland (56)
        • Warsaw (112)
          • Śródmieście (542)
          • Mokotów (595)
        • Wrocław (114)
          • Krzyki (523)
          • Psie Pole (701)
      • Italy (64)
        • Florence (121)
          • Duomo (893)
          • Signoria (894)
          • Scandicci (899)
        • Rome (123)
    • Australia & Oceania (11)
      • Australia (32)
        • Brisbane (68)
          • South Bank (125)
          • Eight Mile Plains (127)
          • New Farm (131)
          • Matter Hill (134)
    • North America (14)

Hypothetical identifiers are in parentheses. Now if you would like to get the oldest parent of beautiful South Bank (located in Brisbane), You will use:

$parents = get_post_ancestors(125);

In return, we will obtain an array:

array(4) { [0]=> int(68) [1]=> int(32) [2]=> int(11) [3]=> int(4) }

The oldest parent of South Bank district is planet Earth (ID 4).