Do you have a parent and child page hierarchy and want to show it on your website?
Then this article you are going to see you how to do it.
You are going to see:
Background of the parent-child pages Background of the parent-child pages
I have categorized the articles into parent and child relationships.
Below is a real-time example of my current blog.
My parent page is Webpack and Its child pages are Blog and How to respectively.
The Blog and How to pages also have their own child pages.
So, I want to show all the child pages in nth depth.
Solutions to display the parent-child page hierarchy Solutions to display the parent-child page hierarchy
WordPress provides a function that returns all the child pages of the parent page.
Get the list of all child pages by parent ID Get the list of all child pages by parent ID
Above function return the list of all child pages of parent page ID 46.
Filter Data Filter Data
It contains the complete object of the page like:
[ID] => 48 [post_author] => 0 [post_date] => 2021-05-11 13:38:47 [post_date_gmt] => 2021-05-11 13:38:47 [post_content] => [post_title] => Blog [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => closed [post_password] => [post_name] => blog [to_ping] => [pinged] => [post_modified] => 2021-05-11 13:38:47 [post_modified_gmt] => 2021-05-11 13:38:47 [post_content_filtered] => [post_parent] => 46 [guid] => https://example.com/wordpress/blog/ [menu_order] => 0 [post_type] => page [post_mime_type] => [comment_count] => 0 [filter] => raw
So, Let’s get only the required fields with PHP array_map()
function as:
$child_pages = array_map( function( $item ) { return array( 'ID' => $item->ID, 'post_title' => $item->post_title, 'post_status' => $item->post_status, 'post_parent' => $item->post_parent, 'post_date' => $item->post_date, 'post_modified' => $item->post_modified, ); }, $child_pages );
Generate the nested hierarchy Generate the nested hierarchy
Now,
We have a filtered page list so let’s build a nested page tree with the below function:
Build HTML Markup Build HTML Markup
Now, We have a nested pages array let’s display it with <ul> and <li> tags.
Use below code snippet to build the HTML markup: