WordPress Child Page Menus

Whilst helping Michelle set up Kids Puzzles and Games I came across the need for the menus in the various sections to show child pages when in a section home page, and peer pages when viewing any content in a section.

The site structure is along the lines of:

  • Home page
    • Section home page
      • Section page
      • Another section page
    • Another section homepage
      • Etc

So in the Colouring Sheets section the menu will show types of colouring sheets, and when viewing a colouring sheet page you will also see types of colouring sheets. For an added twist, as the page titles repeat the name of the section they are in I needed to remove that repetition when displayed in a menu – e.g. Dinosaur Colouring Sheets is the title of a page in the Colouring Sheets section.

Example menu

My PHP isn’t great, and it took me a little while to find examples to put together to make the answer but this seems to do the trick. I’m sharing it in case you need to do something similar.

 // get the title of the parent page
 $parent_title = get_the_title($post->post_parent);
 // get formatted array of child pages but don't echo them
 $child_pages = wp_list_pages('title_li=&child_of=2&echo=0');
 // replace any mention of the parent page title with an empty string
 $child_pages = str_replace($parent_title,'',$child_pages);
 // and now output the menu
 echo $child_pages;

You’ll notice I’ve hard coded the page ID of the parent page – I can do this because each section has it’s own template. I know that $post->post_parent will give the ID of the parent page, but I needed that to be fixed for the section heading and for the section content (which is a child page of the section heading). Feel free to let me know if there is an easier way of doing this I’m all for keeping code simple.

Updated 17th April to remove extra semi-colons added by editing this post on the iPhone WordPress app!