Display every grandchildren on wordpress support forum seems pretty close.
Here is the solution that was proposed:
<ul>
<?php $all = get_pages(); //You could use $args to retrieve posts how you want.
foreach($all as $all) {
if($all->post_parent) {
if( get_page($all->post_parent)->post_parent ) {
$tp = get_page($all->post_parent);
if( !get_page( $tp->post_parent )->post_parent) { $grandchild_ids[] = $all->ID; } //catching all the ids of grandchild or secondchild.
}
}
}
//Usual args parameter & WP_Query loop
$args = array(
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => 5,
'orderby' => 'rand',
'post__in' => $grandchild_ids
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="https://wordpress.stackexchange.com/questions/136128/<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;
}
wp_reset_query(); ?>
</ul>
In summary you would get 5 random posts from the list of grandchildren of all the parents.