Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I guess that this should be an easy one but I haven't yet find the proper solution.

I want to limit the depth of wp_list_pages so as not to display the pages of the last level. So supposing that parent page A has 3 levels of pages I only want to list first 2 levels. I was looking for a function to count the maximum depth of children for a page but no success.

Till now my code is

$parents = get_post_ancestors($post->ID);
if (count($parents)>1) {
    $parent = $parents[count($parents)-2];
} else  {
    $parent = $post->ID;
}

$args = array(
        'depth'        => 0,  // this should be set dynamically
        'child_of'     => $parent,
        'sort_column'  => 'menu_order, post_title',
        'post_type'    => 'page',
        'post_status'  => 'publish'
    ); 

wp_list_pages( $args );

Any help is greatly appreciated

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

This is a little tricky, and my solution may not be the best for the performance. You may add this Value as a Custom Field to the Page, so you do not have to query it everytime.

// get the ancestors of the page, and check if the page is toplevel
$parent = array_reverse( get_post_ancestors( $post->ID ) );
if ( isset( $parent[0] ) ) {
    $toplevel = $parent[0];
} else {
    $toplevel = $post->ID;
}

// get the children of this toplevelpage
$children = get_page_hierarchy( get_pages(), $toplevel );
$depth = 0;
foreach ( $children as $child => $slug ) {

    // check how many ancestors this page has
    $count = count( get_ancestors( $child, 'page' ) );
    // if more than the current depth, set the depth to the new value
    if ( $count > $depth ) {
        $depth = $count;
    }

}
echo $depth; //total depth below this toplevelpage, you can delete this part afterwards

$depth_without_last = $depth - 1;

Just insert the varible instead of the 0 at the depth in your $args, this should work :)

share|improve this answer
    
Hey, thank you for this! The get_page_hierarchy solution works great. BTW your website is awesome! Keep up the good work –  vadims Jan 17 '13 at 13:37
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.