X

Display Back to Parent Page Link with get_post_ancestors

Snippets by IsItWP

Are you looking for a way to create manual breadcrumbs or add a link on sub pages back to redirect users back to parent page? While there’s probably a plugin for this, we have created a quick code snippet that you can use to display back to parent page link with get_post_ancestors in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

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>';
  }
}

Simply add this code snippet in your theme’s template files like single.php, index.php, page.php, etc.

<?php
          wps_parent_post();
?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: How to create a small business website and 7 best WordPress landing page plugins.

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!