How to check if page have subpages or childrens

I needed a function for which would check whether page has subpages/childrens or not. So I came up with this:

Just put this code in functions.php:

function post_have_children($id){
	$children = get_pages('child_of='.$id);
	if(count($children) == 0){
		return false;
	}
	else{
		return true;
	}
}

Ussage:

<?php post_have_children('pageID'); ?>

pageID – the id of the page you want checked, can be used $post->ID which would be current page.

Note: check the quotes, because sometimes when doing copy paste they can be copied as symbols.

Furthermore, if you want to check if parent page has subpages/childrens or page has a parent as a conditional tag you can that by using it like this:

<?php if ( $post->post_parent != 0 || post_have_children($post->ID) ) {
	// Show text if page has a parent or Page is a parent and have children/subpages
 } ?>
On Sep 9, 2010 Posted by and it is filed under: Tutorials, Wordpress

One Response for "How to check if page have subpages or childrens"

While I applaud your efforts here, I would like to point out that every time you run your custom function, post_have_children(), a new database query is generated by WordPress. I would recommend looking into the built in WordPress function get_page_children(). It allows you to fetch the pages once and then caching the results in a variable and use the saved variables as the second parameter in get_page_children().


Leave a reply