30 Apr, 2007
Listing subpages in WordPress
Posted by: Jennifer In: WordPress|WordPress Bookmarks|WordPress Hacks
I was looking for a way to list sub pages in a navigation bar if you were either on the "parent" page or one of it's sub pages. I found this page on Clioweb that was perfect.
What's also nice is that it gives you the variable $parent_id to play with if you need to. Copied from his site:
<?php
$page = $wp_query->post;
$parent_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE ID ='$page->post_parent;'");
if(!$parent_id) $parent_id = $post->ID;
?>
Then, to actually generate the HTML for the page list, I use the following code in the body of my page template:
<?php if(wp_list_pages("child_of=".$parent_id."&echo=0")): ?>
<ul id="subnav">
<?php wp_list_pages("title_li=&child_of=".$parent_id."&sort_column=menu_order&depth=1");?>
</ul>
<?php endif; ?>