Check to See if a Custom Post has any Child Posts
Wow, this on really made my head hurt for a bit.
So I’ve been building a WordPress site hat is using a custom post type of “help.” As you can probably guess, this is for a help section. The data on these help pages is fairly extensive, so I set my post type up to be hierarchical. No problem so far.
Next, I setup a page template for these custom posts (single-help.php). This is where it got a bit tricky; I had three levels of data, all which needed a functional editor so users could input html, and each level needed its own layout, pulling in only its sub posts. So essentially, my page template ended up looking like so (albeit a bit more convoluted).
PHP
<?php // setup your arguments: $args = array( // We want to call all posts the custom post type 'help' 'post_type' => 'help', 'posts_per_page' => -1, 'post_status' => 'publish', 'order' => 'ASC', // Next, we want to see if the current post is a parent of any help posts 'post_parent' => $post->ID ); // We then pass these to a wordpress query, and setup our loop $loop = new WP_Query( $args ); ?> <?php if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post(); ?> <!-- This post has children, so we'll list them out --> <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a> <?php endwhile; ?> <?php else : ?> <!-- This post has no children --> <?php endif; ?>
So basically, this code allowed my single-help file to handle all three levels of the help page hierarchy, loading in each when necessary.
Lemme know your thoughts. I’d love to clean this up a bit more.
Comments (5)
Leave a Reply
This was just what I needed!
You could use “get_post_type()” in place of the specific post type to make it work with multiple custom post types.
ex.
Link to comment$args = array(
// We want to call all posts the custom post type ‘help’
‘post_type’ => ‘get_post_type()’,
Cool, thanks Melissa!
Link to commentI spent my day searching for a way to check if the post has children and this really helped me a lot. Thanks bud. Much appreciated 🙂
Link to commentNice, but what happens if you limit my ‘posts_per_page’ and need to use the pagination? Is it possible?
Link to commentI spend many time to search children post data and this really helped me a lot. Thunk you very much.
Link to comment