Wednesday, December 1st, 2010 | Tips, WordPress

Easy way to check for child pages (children) in WordPress

I was trying to create a sub-navigation menu that would only show if there were child pages in WordPress the other day, but to my knowledge, there is no has_children() or has_child() type of conditional available. I’m sure it’s because there are so many other ways to check for children. Still, it would be nice. But here’s how I did it, feel free to copy my code.

In any single.php template, use this code:

Using $post->ID

<?php

$pages = get_posts('numberposts=-1&orderby=menu_order&order=ASC&post_type=page&post_status=publish&post_parent='.$post->ID);

if (!empty($pages)) {

$has_children = true; // Page has children

} ?>

Using get_the_ID()

<?php

$the_ID = get_the_ID();

$pages = get_posts('numberposts=-1&orderby=menu_order&order=ASC&post_type=page&post_status=publish&post_parent='.$the_ID);
if (!empty($pages)) {
$has_children = true; // Page has children

} ?>

Now you’re even set to loop through your pages to create your sub-menu.

Hope someone finds that helpful

Further Reading

Filed Under: Tips, WordPress

Leave a Comment