0

Having for example the following page hierarchy

Page1
 - SubPage1_1
 - SubPage1_2
 -- SubSubPage1_2_1

Page2
 - SubPage2_1
 - SubPage2_2
 -- SubSubPage2_2_1

and requesting for example SubSubPage1_2_1 how can I get with wp_list_pages the hole hierarchy? The expected result

Page1
     - SubPage1_1
     - SubPage1_2
     -- SubSubPage1_2_1

I have been trying the following

global $post;

if(!$post->post_parent){
    // will display the subpages of this top level page
    $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
}
else{

    if($post->ancestors) {
        // now you can get the the top ID of this page
        // wp is putting the ids DESC, thats why the top level ID is the last one

        $ancestors = get_post_ancestors($post);
        $children = wp_list_pages("title_li=&child_of=".implode($ancestors, ',')."&echo=0");
    }
}

but in my case does not output the desired result

0
0

You can do it like so:

if ( ! $post->post_parent ) {
    $pages = get_pages( 'child_of=' . $post->ID );
    $pages = $pages ? wp_list_pluck( $pages, 'ID' ) : '';
    $includes = $post->ID . ( $pages ? ',' . implode( ',', $pages ) : '' );
    $children = wp_list_pages( 'title_li=&include=' . $includes . '&echo=0' );
} else {
    $pages = get_post_ancestors( $post );
    $includes = $post->ID . ',' . implode( ',', $pages );
    $children = wp_list_pages( 'title_li=&include=' . $includes . '&echo=0' );
}
echo $children ? "<ul>$children</ul>" : '';

I.e. Use the include parameter.

For top-level pages (post_parent is 0), $children = wp_list_pages( 'title_li=&child_of=' . $post->ID . '&echo=0' ); works as well, but doesn't include the parent's markup (LI) itself unless you manually add it. And I prefer of having the markup/LI be generated by wp_list_pages().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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