This is the clean and nice code you need:
It is also retained for use when there is more than one level of parental hierarchy.
<?php $current = $post->ID; $parent = $post->post_parent; $grandparent_get = get_post($parent); $grandparent = $grandparent_get->post_parent; ?> <?php if ($root_parent = get_the_title($grandparent) !== $root_parent = get_the_title($current)) {echo get_the_title($grandparent); }else {echo get_the_title($parent); }?>
Thomas maier
source share