• I’m trying to build a loop that displays content from a custom post type, and if the post has child pages, loop through and show content from the child pages.

    Should end up with something like this:

    <div id="myloop">
    
       <div class="post no-children">
          <h2>Post Title</h2>
          <p>Post excerpt</p>
       </div>
    
       <div class="post parent has-children">
          <h2>Post Title</h2>
          <p>Post excerpt</p>
             <div class="child">
                <h3><a href="child-permalink">Child Post title</a></h3>
                child thumbnail image
                <p>Child excerpt</p>
             </div>
       </div>
    
       <div class="post no-children">
          <h2>Post Title</h2>
          <p>Post excerpt</p>
       </div>
    
       <div class="post parent has-children">
          <h2>Post Title</h2>
          <p>Post excerpt</p>
             <div class="child">
                <h3><a href="child-permalink">Child Post title</a></h3>
                child thumbnail image
                <p>Child excerpt</p>
             </div>
       </div>
    
    </div>

    Is this possible? I’m just not familiar enough with queries to make this happen.

Viewing 1 replies (of 1 total)
  • Thread Starter thunderdunk

    (@thunderdunk)

    I think I’ve almost got it working, but it’s showing the parent post content (and repeating it endlessly) where it should be showing child post content. Here’s what I have–am I close, at least?

    <?php
    $args = array('post_type' => 'tc_condition', 'orderby' => 'title', 'order' => 'ASC', 'post_parent' => 0, 'posts_per_page'=>'-1');
    $query1 = new WP_Query($args);
    
    if($query1->have_posts()) : while($query1->have_posts()) : $query1->the_post(); ?>
    
       <div class="parent">
    
          <h2><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
             <div class="child">
                   <?php
    		// initialization for $inner_args & backup the current global $post
    		$inner_args = array('post_type' => 'tc_condition', 'post_parent' => $post->ID, 'posts_per_page' => 5);
    		$inner_query = new WP_Query($inner_args);
    
    		global $post;$backup=$post;
    
    		while ($inner_query->have_posts()) : ?>
    			    <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
    		<?php
    		endwhile;
    		// restore the global $post from the previously created backup
    		$post=$backup;	?>
    
             </div><!--.child-->
          </div><!--.parent-->
    
    	<?php endwhile; else: ?>
    		<p>You didn't say the magic word...</p>
    		<?php wp_reset_postdata(); // reset the query ?>
    	<?php endif; ?>
Viewing 1 replies (of 1 total)
  • The topic ‘Display page and child page content in loop’ is closed to new replies.