Subnav: Show Parent and Child on Grandchild Page

Stumbled across this bit of code here. Used to show the main navigation in a sidebar for all child and grandchild pages.

The code that generates the full menu (place in functions.php):

if(!$post->post_parent){

	// will display the subpages of this top level page
	$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");

}else{

        // displays only the subpages of parent level
        //$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");

        if($post->ancestors) {

               // now you can get the the top ID of this page
               // wp is putting the ids DESC, thats why the top level ID is the last one

	       $ancestors = end($post->ancestors);

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

	       // you will always get the whole subpages list
	}
}

Place where you would like the menu to appear:

if ($children) { ?>

	<div id="submenu_container"><div class="sub_menu">

	

		<ul>

			<?php echo $children; ?>

		</ul>

	</div></div>



<?php }

 

Leave a Reply

Posted in php
katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.