Below is a step by step guide on how to create a menu of child pages by using the post ID of a child page.
It uses that ID to get the top parent’s slug, then the top parent’s ID and finally uses the wp_list_pages() function of WordPress to retrieve and display the list of child pages.
Get slug of top parent
Firstly, you need to add the function below called getTopParentPostName(). This function gets the slug of the top parent of the subpage we are on. We need this so that we can then get the ID of the
Get top parent’s ID
Next we need to use the function get_ID_by_slug() to get the ID of the top parent we just found. This is so we can use the list in the array of arguments in the wp_list_pages() function in WordPress.
Displaying the child pages
Finally we use create the array of arguments we want so we can compile the menu of subpages. This is done using the wp_list_pages() function and passing an array of arguments to it.
The arguments I have used do the following things:
‘echo’ => 1 – this allows the function to echo the menu out once we call it.
‘title_li’ => ” – this just removes the title of the menu…I don’t usually fel the need to display this, that’s all.
‘child_of’ => get_ID_by_slug(getTopParentPostName($post->ID)) – this uses the post ID of the page we are on to then get the top parent slug, then the ID of that top parent. This ID is then used to get all the children of that ID for displaying in the menu.
‘sort_column’ => ‘menu_order, post_title’ – this is just a way to order the items in the menu. It does it by the order you gave them when adding them and then by title alphabetically.
Full Whammy…
So the full code you will need to add to pull out the child pages from a post ID is: