Loop to show WP pages, their children and their grand children and content of each
Question
I needed to make a loop to get a list of pages and show the children and grandchildren for each page, as well as truncated content of each result. I couldn’t find this as a question anywhere and this is what I came up with. This works as is, so I wanted to document what I’ve found and ask for help cleaning it up for others if they needed similar.
<?php
$args2 = array(
//'cat' => 7,
'post_type' => 'page' ,
'post_status' => 'publish',
'posts_per_page' => 2,
'post__in' => array( 10, 1987) ,
);
$the_query1 = new WP_Query( $args2 );
$title_content = "50";
$content_length2 = "140";
?>
<? if ( $the_query1->have_posts() ) : ?>
<!-- pagination here --><!-- the loop -->
<?php while ( $the_query1->have_posts() ) : $the_query1->the_post(); ?>
<div class="row">
<div class="medium-9 small-9 columns article-thumb">
<a href="<?php the_permalink();?>"><?php echo truncate(strip_tags(get_the_title()),$title_content); ?></a>
<p class="p-16x"><?php echo truncate(strip_tags(get_the_content()),$content_length2);?>...</p>
<?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 class="child1">', '</h3>');
echo truncate(strip_tags(get_the_content()),$content_length2);?>
<?php $gchildren = new WP_Query( array('post_type' => 'page', 'post_parent' => get_the_ID() )); ?>
<?php if ( $gchildren->have_posts() ) : ?>
<ul class="post-gchildren">
<?php while ( $gchildren->have_posts() ) : $gchildren->the_post(); ?>
<li><?php the_title('<h4>', '</h4>');
echo truncate(strip_tags(get_the_content()),$content_length2);?>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
</div>
</div>
<?php endwhile; ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
0
children, pages
3 years
2019-10-21T13:03:22-05:00
2019-10-21T13:03:22-05:00 0 Answers
90 views
0
Leave an answer