Loop over WordPress child posts and link to the next post in a hierarchical sequence

by Dan
Last updated: September 26th, 2020

Following on from our previous code snippet which showed us how to detect if a WordPress post is a child or parent post, this snippet looks up the current posts parent, loops over all children, understands its position in the sequence, and then returns a link to the next child post in the sequence.

I found this particularly useful when creating an online course platform for a client where each part of the course had to be completed in a hierarchical order, providing a handy link to the next lesson in the sequence once the current lesson was marked complete.

// Loop over posts and fetch the link to the next post in the sequence $all_posts = new WP_Query(array( 'post_type' => 'courses', // our post type 'posts_per_page' => -1, // fetch all posts 'orderby'=>'menu_order', 'order' => 'ASC', 'post_parent' => wp_get_post_parent_id($post->ID), // get the current posts parent )); // loop over child posts and find the next post in the sequence foreach($all_posts->posts as $key => $value) { if($value->ID == $post->ID){ $nextID = $all_posts->posts[$key + 1]->ID; break; } } // render a link to the next post if($nextID): ?> <span class="next"> <a href="<?= get_the_permalink($nextID) ?>" rel="next"><?= get_the_title($nextID) ?></a> </span> <?php endif; ?>

we think you'll probably like these too