When viewing single parent post, display list of children

Try this, it’s the most basic implementation. It could be more effecient to hook into pre_get_posts, and change the query from a ‘top level page’ to a query for it’s children. But that has the potential to break a few things, and in particular would probably require you to alter the template used.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();  ?>

    <header class="entry-header">
        <h1 class="entry-title"><?php the_title(); ?></h1>
    </header><!-- .entry-header -->

    <?php   //If top level, find children
        if($post->post_parent == 0):
            $children = new WP_Query(array(
                'post_type'=>'page',
                'post_parent'=>$post->ID
            ));

            if($children->have_posts()): ?>
                <ul>
                <?php while ( $children->have_posts() ) : $children->the_post(); ?>
                    <li> <?php the_title();?> </li>
                <?php endwhile; ?>
                </ul>

            <?php else: ?>
                <?php echo 'No children';?>
            <?php endif; ?>

            <?php wp_reset_postdata(); ?>
        <?php else://Not top level, display normal post ?>
            <?php the_content(); ?>
        <?php endif;?>

    <?php endwhile; // end of the loop. ?>
<?php endif; ?>

Leave a Comment