WordPress Heirarchical Sidebar Page Menus

Let’s say you want to show a hierarchical sidebar menu that displays a listing of current subpages. This is easy enough, but let’s say that you have a top menu that shows all top-level pages. Once you click on a top level page from that menu it will take you there and in the sidebar show all subsequent child pages. Now what if those child pages have a child? You don’t want all menu items to disappear when you click on one of those child pages. That just looks funny. Here’s the bit of code that works great for me:

[inline]
[code lang=”PHP”]
<?php
if ((count($post->ancestors) > 0)
&& ($data = array_reverse($post->ancestors))
&& !is_null($data[0])){
$data = wp_list_pages(‘title_li=&echo=0&child_of=’.$data[0]);
} else {
$data = wp_list_pages(‘title_li=&echo=0&child_of=’.$post->ID);
}
if (strlen($data) != ”) {?>
<ul class=’nav’><?php echo $data; ?></ul>
<?php } ?>
[/code]
[/inline]