Brett
Brett

Reputation: 887

Wordpress Sub Navigation Menus in Sidebar

I have a WordPress site with the following structure

Page 1
   Sub Page 1
   Sub Page 2
Page 2
   Sub Page 1
      Sub-Sub Page 1
      Sub-Sub Page 2
      Sub-Sub Page 3
   Sub Page 2
   Sub Page 3

When on any Sub-Sub page, I want to list the Sub Page(s) in a sidebar navigation.

Using the code below as a starting point...which doesn't work on Sub-Sub pages because it is showing the Sub-Sub pages in the navigation and not the Sub pages.

<?php
  if($post->post_parent)
  $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
  else
  $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
  if ($children) { ?>
  <ul>
  <?php echo $children; ?>
  </ul>
<?php } ?>

Thanks

Brett

Upvotes: 1

Views: 3516

Answers (2)

Brett
Brett

Reputation: 887

Got it working. This is the final code (pulled from http://cssglobe.com/post/5812/wordpress-find-pages-top-level-parent-id with little modification)

<?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&depth=1");

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

Upvotes: 3

Ben
Ben

Reputation: 26

Brett,

You'll have to check and see if there is a post grandparent and then use the id of the post grandparent. You can probably use the get_post_ancestors() function to find out how many ancestors there are and then adjust your code accordingly.

Upvotes: 1

Related Questions