Using the Loop to show all levels of subpages under a parent page? Halfway there

Sounds like you’re looking for a recursive function, ie a function that calls itself. Here’s a rough outline of how it can be done:

function wpse13669_show_all_children( $post_id, $current_level ) {
    $children = get_posts( array(
        'post_type' =>'page',
        'posts_per_page' =>-1,
        'post_parent' => $post_id,
        'order_by' => 'title',
        'order' => 'ASC' ) );
    if ( empty($children) ) return;

    echo '<ul class="children level-'.$current_level.'-children">';

    foreach ($children as $child) {

        /* Here would be the point where you
            do whatever you want to display the 
            posts. The variable $current_level can
            be used if you want to style different 
            levels in the hierarchy differently */

            echo '<li>';

        echo '<a href="'.get_permalink($child->ID).'">';
        echo apply_filters( 'the_title', $child->post_title );
        echo '</a>';

        // now call the same function for child of this child
        wpse13669_show_all_children( $child->ID, $current_level+1 );

            echo '</li>';

        }

    echo '</ul>';

    }

Note: edited my code to show the kind of nested <ul> lists it sounds like you’re looking for. If you want to see how WordPress does stuff like this internally (its a lot more complicated than this, but worth figuring out if you need to do anything really custom in your code), you should look through the source code for the class-wp-walker.php file, where the Walker class that handles all the various nested lists (menus, comments, page lists, etc) throughout WP.

If you define that function with the output structure you want and just call it from within your loop, it should do what you’re looking for. I put a $current_level variable in there just so that you can easily style children different from grand-children, and so on.

(within your main loop)

wpse13669_show_all_children( $post->ID, 1 );

Leave a Comment