Various code for Parent & Grandparent pages in WordPress

Show parent page title regardless of what subpage you are on:

if($post->post_parent) {
    $parent_title = get_the_title($post->post_parent);
    echo $parent_title;
} else {

Find Page’s Top Level Parent ID

This code can be used for displaying 2nd and 3rd level navigation links based on the current section.
Code taken from the CSS Globe here:


if ($post->post_parent)	{
	$parent = $ancestors[$root];
} else {
	$parent = $post->ID;

$children = wp_list_pages("title_li=&child_of=". $parent ."&echo=0");

if ($children) { ?>
<ul id="subnav">
<?php echo $children; ?>
<?php } ?>

Display a link to the top-level page of a section

<?php /*is the homepage the granparent?*/ if ($grandparent == is_page('0')) { ?>
 <a href="<?php echo get_permalink($grandparent); ?>">Back to <?php echo $grandparent_title; ?></a><br/>
 <a href="<?php echo get_permalink($post->post_parent); ?>">Back to <?php echo $parent_title; ?></a>
 <?php /*is the homepage the parent?*/ } elseif ($post->post_parent ==is_page('0')) {?>
 <a href="<?php echo get_permalink($post->post_parent) ?>">Back to <?php echo $parent_title; ?></a>
 <?php /*I must be a top level page!*/ } else { ?>
 <!-- no parent to show -->
 <?php }?>

Find all the ancestor ID’s of a page up to greatgrandparent

$current = $post->ID;
$parent = $post->post_parent;
$get_grandparent = get_post($parent);
$grandparent = $get_grandparent->post_parent;
$get_greatgrandparent = get_post($grandparent);
$greatgrandparent = $get_greatgrandparent->post_parent;
echo "parent = $parent; grandparent = $grandparent; greatgrandparent = $greatgrandparent";


There are no revisions for this post.

Tags: , ,

No comments yet.

Leave a Reply