3

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?

5

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.

0

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.

  • This will return the immediate parent, not necessarily the top level parent as requested. Think about what would happen with children nested 3 or 4 deep. – s_ha_dum May 30 '13 at 14:36
  • Good point -- I missed the "sub sub" when I first read the question! – sabreuse May 30 '13 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.