how to properly list child pages in sidebar?

My pages menu is maximum 3 levels deep and I am having a hard time figuring out how to properly list the child pages in the sidebar.

If a page is a parent I want to list it’s direct child pages and the title should be this parent.

Read More

If a page is a child AND has children of itself, I want to list only it’s children and the title should be this page

If a page is a grandchild, I want to list it’s siblings and the title should be this grandchild.

For now I am using (from the Codex):

<?php if($post->post_parent) {
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0&depth=1&sortcolumn=menuorder");
} else {
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0&depth=1&sortcolumn=menuorder");
}
?>
<?php if ($children) { ?>
<div class="left-bar-content">
<h2><?php _e('More ','sunchine') ?><?php echo get_the_title($post->post_parent);?></h2>
<ul class="leftbar-list">
<?php echo $children;?>
</ul>
</div><!-- .left-bar-content -->
<?php
}
?>

And this is almost correct. Almost, because my it doesn’t do my 2nd criterium.

The Codex has heaps of options, but I cannot figure out which would be applicable to what I want to accomplish. Using widgets and/or a plugin is not an option.

Any help is much appreciated.

Related posts

Leave a Reply

1 comment

  1. Here is the code that satisfies all your 3 requirements above.

    <?php
    /*
     * get_page_depth
     * Gets the page depth, calls get_post on every iteration
     * https://gist.github.com/1039575
     */
    if ( !function_exists( 'get_page_depth' ) ) {
    function get_page_depth( $id=0, $depth=0 ) {
        global $post;
    
        if ( $id == 0 ) 
            $id = $post->ID;
    
        $page = get_post( $id );
        if ( !$page->post_parent ) {
                // this page does not have any parent
                return $depth;
        }
        return get_page_depth( $page->post_parent, $depth+1 );
    }
    }
    
    $target_page = get_page_depth( $post->ID ) > 1 ? $post->post_parent : $post->ID;
    $children = wp_list_pages("title_li=&child_of={$target_page}&depth=1&echo=0&sort_column=menu_order");
    
    ?>
    
    <div class="left-bar-content">
        <h2><?php _e('More ','sunchine'); ?><?php echo get_the_title( $target_page ); ?></h2>
        <ul class="leftbar-list">
            <?php echo $children; ?>
        </ul>
    </div><!-- .left-bar-content -->