X

Display back to parent page link with get_post_ancestors

Adding the first snippet to the functions.php of your wordpress theme will display a link on sub pages back to the top level parent page. Place the second snippet within your theme in the location you want to display the link.


function wps_parent_post(){
  global $post;
  if ($post->post_parent){
	$ancestors=get_post_ancestors($post->ID);
	$root=count($ancestors)-1;
	$parent = $ancestors[$root];
  } else {
	$parent = $post->ID;
  }
  if($post->ID != $parent){
      echo '<a href="'.get_permalink($parent).'" class="parent-post">Back to parent page</a>';
  }
}
<?php
          wps_parent_post();
?>

Comments  Leave a Reply

  1. I used this on a site, but it is causing the top level pages to 404 unless I flush the rules regularly. Thoughts? Thanks

  2. Thanks for the snippet. Although it always points to the ‘root’ page, i.e. if I am on a grandchild page, it links to the grandparent instead of the parent.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!