Sub Pages in WordPress | Wordpres Theme Development | Lesson 4

In this lesson we will learn that, How can we create sub pages in WordPress to a parent page. This is very simple and to perform this task we have a predefined function i.e wp_list_pages().

If you use this function anywhere in your PHP code, it will return the list of all pages.

Sub Pages in WordPress


For enabling the feature of subpages to a parent page, we have to use this function with passing some parameters.

So let’s begin with this.

First, we have created four pages with dummy content with WordPress admin area (1 Parent page and 3 Child/subpages)

Parent Page:
About Us
Sub/Child Pages:
1. Mission Statement
            2. Our Future
            3. Our History

Now in our page.php we have to use discussed function wp_list_pages() with an array argument.

 Explanation: In above code, almost all code is same like previous but we added a new function wp_list_pages() and right above that function we created an array ($args) with the keys ‘child_of’ and ‘title_li’.

Now first, into the array $args the first key-value pair is

‘child_of’ => $post->ID for instruct the function to show all the child pages of current post or page.
And the second key-value pair is
‘title_li’ => ” for erase the title of list.

Now our page will look like

Sub Pages in WordPress

Now take this example to something advance level.

If you will try the above code, then you will feel that the child pages menu is showing only on the parent page, in our case i.e About Us. But we want the same appearance of this menu into our child pages (Mission statement, Our Future, Our History).

So now, we have created a self-declare function get_top_ancestor_id().

Declaration of get_top_ancestor_id()

Add the following code snippet into functions.php

Remember: All self-created functions will be declare only functions.php

global $post;                         -Make the variable $post, global so that we can use this predefine variable into our functions
if($post->post_parent)          – Execute if the current post has any parent



The function get_post_ancestors($post->ID) will give us a array of the passing post’s parent.

$post      ->            Grand Grand Parent> Grand Parent>Parent

Array_reverse() function will reverse the passing array’s elements.

$ancestors[0];       -> we are trying to retrieve the first value of ancestors array. Because this value is for the parent ID of $post.

Now we updated our page.php file as follows:

Explanation: Now in this updated code we added some HTML elements like <span>, <ul> and <nav> with self-created CSS classes.


And CSS for style.css will be:

Now Finally, We have the out of which we were done,

Sub Pages in WordPress

That’s all in this lesson. Hope you learn and enjoy this lesson. Now take a rest and be ready for next lesson of this series.