Get Permalink for the top level parent of child pages

I’ve this pages structure:

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

Related posts

2 comments

  1. 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.

  2. You can get the post ID of the parent page with $post->post_parent; at that point, it’s just a matter of using that ID to get the permalink.

    This snippet from the wp.org forums will do what you need:

    <?php if($post->post_parent) {
        $parent_link = get_permalink($post->post_parent); ?>
        <a href="<?php echo $parent_link; ?>">Link to parent page</a>
    <?php } ?>
    

    Code snippet found here.

Comments are closed.