Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Some use this to get the top page url:

<?php $top_page_url = get_permalink( end( get_ancestors( get_the_ID(), 'page' ) ) );?> 

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. By using the PHP function end() we get the last array item. You can read more about it here.

share|improve this answer
    
Thank you! It works perfectly! –  Pepozzo May 30 '13 at 15:57
    
ok great, if the answer solved your problem then please mark it as accepted, thanks ;-) –  birgire May 30 '13 at 16:00

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.

share|improve this answer
    
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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