Here's a short WordPress code that I wanted to share with you. I came across a little problem of displaying 2nd and 3d level of navigation in a sidebar no matter what page am I on. After googling for solution, I put together a pieces of a puzzle and came up with a short code snippet.
I created a new page in my theme that I'll be using from now on for displaying side navigation from 2nd level downwards. I named it subnav.php and it's included in my sidebar.php
<?php include("subnav.php"); ?>
Here's the code from my subnav.php:
<?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");
if ($children) { ?>
<ul id="subnav">
<?php echo $children; ?>
</ul>
<?php } ?>
This code checks if the page we're on (current page) has a parent. If so, that means that we are at least 2 levels deep in the navigation. In that case function get_post_ancestors is called. It returns an array of all the ancestors' IDs up to the top level (root).
To get the ID of the top level ancestor we need to fetch the last item in that array.
On the other hand, if the page we're on doesn't have a parent it means we are currently on a top level page so we can use the current page ID.
Once we get the ID of the top level parent we can use it in wp_list_pages function to get its children.
Short'n'sweet, hope it helps somebody. :) I'll be using it that's for sure!
Designer, developer and a passionate standardista. Long time web professional with huge experience in all types of front-end work. Founder of Css Globe and creator of
Tyrone Avnit on 9 Aug, 2009 wrote:
Sarah Lewis on 18 Aug, 2009 wrote:
I really appreciate you taking the time to document your solution!
Sudar on 19 Aug, 2009 wrote:
Single Maria on 26 Aug, 2009 wrote:
teknoloji on 31 Aug, 2009 wrote:
JonnyPage on 3 Sep, 2009 wrote: