Get Permalink for the top level parent of child pages

I’ve this pages structure:

  • TOP PAGE

    • SUB PAGE 1
      • SUB SUB PAGE 1
    • SUB PAGE 2

    [etc]

Is it possible to display on each sub page a link to come back to the top level page? And how?

2 Answers
2

Here’s a way to get the top page url:

$top_page_url = get_permalink( array_slice( get_ancestors( get_the_ID(), 'page' ) , -1 ) );

where get_ancestors() returns an array containing all the parents (ID) of the given page. You can read more about it in the Codex here.

Here are various ways to get the last array item, but note that end() doesn’t expects a function as an input – more about it in the PHP docs here.

Leave a Comment