Navigation Menu for sections based on parent and grandparent

This is pretty awesome! I needed to have a sub-navigation links menu using the wp_list_pages function for sections and child pages. I needed the menu to display appropriately if it’s a second-level page with only a parent pageĀ  and also if it is a third-level page making the top-level page of the section a grandparent page. Here’s the solution:

This code came from the wordpress support forums here: http://wordpress.org/support/topic/348910

<?php
 if(!$post->post_parent){
 // will display the subpages of this top level page
 $master = wp_list_pages("title_li=&include=".$post->ID."&child_of=".$post->post_parent."&echo=0&depth=1");
 $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0&depth=1");
 }else{
 // diplays only the subpages of parent level
 //$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0&depth=1");

 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);
 $post_ancestors = get_post_ancestors($post);
 $master = wp_list_pages("title_li=&include=".array_pop($post_ancestors)."&echo=0&depth=1");
 $children = wp_list_pages("title_li=&child_of=".$ancestors."&echo=0&depth=1");
 // you will always get the whole subpages list
 }
 }

 if ($children) { ?>
 <ul>
 <?php echo $master . $children; ?>
 </ul>
<?php } ?>

Revisions

There are no revisions for this post.

Tags: , , , , ,

No comments yet.

Leave a Reply