Home > Development > WordPress > Sub-page Count > Version 0.4

I’ve wrapped up everything into a nice tidy function. This is also compatible with WordPress v4.2.

This also allows for a page meta to be set called “display_children” with a value of either “desc” or “asc”.

<?php
subpage_count($postID){
	if(is_page($postID) && get_children($postID)){
		$meta = get_post_custom($postID);
		if(strtolower($meta['display_children'][0]) === 'desc') $children = wp_list_pages('title_li=&child_of='.$postID.'&echo=0&depth=1&sort_order=desc');
		else $children = wp_list_pages('title_li=&child_of='.$postID.'&echo=0&depth=1&sort_order=asc');
 
		if($children){
			preg_match_all('#<li class="page_item page-item-(.*?)">#msi', $children, $childrenIDs);
 
			foreach($childrenIDs[1] as &$childID){
		    	$count   = count(explode("\n", wp_list_pages('title_li=&child_of='.$childID.'&echo=0&depth=1&sort_order=desc'))) - 1;
		    	$match[] = '#<li class="page_item page-item-'.$childID.'"><a href="(.*?)" title="(.*?)">(.*?)</a></li>#msi';
 
		    	if(intval($count) !== 0) $replace[] = "\t".'<li><a href="$1" title="$2">$3 ('.$count.')</a></li>';
		    	else $replace[] = "\t".'<li><a href="$1" title="$2">$3</a></li>';
			}
			return '<ul>'."\r\n".preg_replace($match, $replace, $children).'</ul>'."\r\n";
		}
	}
}
?>