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.
I used this on a site, but it is causing the top level pages to 404 unless I flush the rules regularly. Thoughts? Thanks
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.