Various code for Parent & Grandparent pages in WordPress

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

<?php
if($post->post_parent) {
    $parent_title = get_the_title($post->post_parent);
    echo $parent_title;
} else {
    wp_title('');
}
?>

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: http://cssglobe.com/post/5812/wordpress-find-pages-top-level-parent-id

<?php

if ($post->post_parent)	{
	$ancestors=get_post_ancestors($post->ID);
	$root=count($ancestors)-1;
	$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; ?>
</ul>
<?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

<?php
$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";
?>

Revisions

There are no revisions for this post.

Tags: , ,

No comments yet.

Leave a Reply