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:

 // 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");
 // diplays only the subpages of parent level
 //$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0&depth=1");

 // 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) { ?>
 <?php echo $master . $children; ?>
<?php } ?>


There are no revisions for this post.

Tags: , , , , ,

No comments yet.

Leave a Reply