Wordpress Sub-nav

I spent a much bigger chunk of my day than I had anticipated getting a reliable third-level nav component built in Wordpress. Either the third-level wouldn't show up, or *only* the third-level would show up, or the entire nav tree would show up on every page, or the second-level pages would only show the second-level nav and the third-level pages would only show the third-level nav.

The code I ended up with was simple; figuring out this code was not.

$anc = get_post_ancestors($post);
// if there are more than one ancestor pages, show the section tree
if (count($anc) > 1) {
wp_list_pages("title_li=&child_of=$anc[1]&depth=2");

// otherwise show the flat section nav
} else {
wp_list_pages("title_li=&child_of=$parent&depth=2");
}

Addendum: looks like I included an undefined variable. $parent looks like this (and makes me think there's a more elegant way to combine both of these):

if(empty($wp_query->post->post_parent)) {
$parent = $wp_query->post->ID;
} else {
$parent = $wp_query->post->post_parent;
}

Posted on May 27, 2010

More by Dave Shea

View profile