WordPress: Find Page’s Top Level Parent ID

By Posted in - Web Design Tips on August 18th, 2009 0 Comments

Here’s a short WordPress code that I wanted to share with you. I came across a little problem of displaying 2nd and 3d level of navigation in a sidebar no matter what page am I on. After googling for solution, I put together  pieces of a puzzle and came up with a short code snippet.

I created a new page in my theme that I’ll be using from now on for displaying side navigation from 2nd level downwards. I named it subnav.php and it’s included in my sidebar.php

<?php include("subnav.php"); ?>

Here’s the code from my subnav.php:

<?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 } ?>

This code checks if the page we’re on (current page) has a parent. If so, that means that we are at least 2 levels deep in the navigation. In that case function get_post_ancestors is called. It returns an array of all the ancestors’ IDs up to the top level (root).
To get the ID of the top level ancestor we need to fetch the last item in that array.
On the other hand, if the page we’re on doesn’t have a parent it means we are currently on a top level page so we can use the current page ID.

Once we get the ID of the top level parent we can use it in wp_list_pages function to get its children.

Short’n’sweet, hope it helps somebody. 🙂 I’ll be using it that’s for sure!


Copyright: Css Globe

Please leave a Comment