Every now and then, I need to display a list of all the child pages of a top level page in WordPress. This might be for a sub menu, or listing of some kind, for a page that we know the slug for, but that we don’t want to go to the effort of finding the ID for. I think this is a nicer solution in case the database is migrated, although name changes are probably going to affect it more I guess on reflection.
Anyways, the function I use is this…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// get children pages of passed page function childrenInformation($name){ global $post; $thispage = $post; $result = new WP_Query('pagename=' . $name); $lookup = array( 'post_parent' => $result->post->ID, 'post_type' => 'page', 'order' => 'ASC', 'orderby' => 'menu_order' ); $childpages = get_children($lookup); // if the page has children, spit them out. if(count($childpages) > 0){ foreach($childpages as $k => $post){ setup_postdata($post); echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; } } $post = $thispage; } |
$post is captured at the beginning of the function incase you call this half way through a post – therefore it’s not affected.
Simply call it like this
1 |
childrenInformation('about-us'); |
Image Credit: quas
Comment or tweet @douglasradburn