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();
?>

Be Sociable, Share!

Leave a comment