2

I am trying to develop a query for WordPress that will allow me to display a list of child pages with titles only, and then under each child page title, a list of grandchilden (children of the child) page titles AND their content.

So for example, the output should be something like this:

<ul>
  <li>
    <h1>Page 1</h1>
    <ul>
      <li>
        <h2>Child Page 1</h2>
      </li>
      <li>
        <h2>Child Page 2</h2>
        <ul>
          <li>
            <h3>Grandchild</h3>
            <p>Hello, welcome to this grandchild page</p>
          </li>
          <li>
            <h3>Grandchild #2</h3>
            <p>Hello, welcome to this grandchild page</p>
          </li>
        </ul>
      </li>
      <li>
        <h2>Child Page 3</h2>
      </li>
    </ul>
  </li>
  <li>
    <h1>Page 2</h1>
  </li>
</ul>

It needs to be done dynamically, meaning I do not want to specify the post ID number as part of the query.

I have tried using a standard WordPress Query and then nesting a second query within the first one - this failed.

In addition, I also tried modifying the code seen here: http://wordpress.org/support/topic/query-child-pages-of-a-current-page-and-loop-through-each-child-page

Finally, I also tried to modify this code:

<?php if ( have_posts() ) {  while ( have_posts() ) { the_post(); $thispage=$post->ID; }} ?>
<?php $childpages = query_posts('post_per_page=3&orderby=menu_order&order=asc&post_type=' . get_post_type( $post->ID ) . '&post_parent='.$thispage);
    if($childpages){ /* display the children content  */
            foreach ($childpages as $post) :
            setup_postdata($post); ?>
          <li><a class="" href="#<?php echo($post->post_name) ?>">
            <?php the_title(); ?>
            </a></li>
          <?php
      endforeach;
     } ?>

I've been trying to get this working for more than a day now and i'm just going around in circles really.

Would very much appreciate help in getting this working.

1 Answer 1

3

Try something like:

<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
        <div class="parent-post">
            <?php the_title('<h2>', '</h2>'); ?>
            <?php $children = new WP_Query( array('post_type' => 'page', 'post_parent' => get_the_ID() )); ?>
            <?php if ( $children->have_posts() ) : ?>
            <ul class="post-children">
                <?php while ( $children->have_posts() ) : $children->the_post(); ?>
                    <li><?php the_title('<h3>', '</h3>'); the_content(); ?></li>
                <?php endwhile; ?>
            </ul>
            <?php endif; ?>
    <?php endwhile; ?>
<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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