I have the following structure of pages, and I need to have that same structure displayed on those pages who have child pages:

- Childpage
- - Grandchildpage
- - Other Grandchildpage
- Other Childpage

The following code is used to display the structure on page.php:

<ul class="sidemenu-list">
        $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=1");
        $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=1");
        if ($children) { ?>
            <?php echo $children; ?>
    <?php } ?>

This works when on the parent page. But when I'm on one of the childpages or grandchild pages, this doesn't work anymore.

Following above structure example, when I'm on 'Childpage' I only get the following:

- Childpage
- Other Childpage

And when I'm on 'Grandchildpage' I only get:

- - Grandchildpage
- - Other Grandchildpage

What is the correct way to display the page hierarchy even when the page is a child or grandchild?

1 Answer 1


It is quite obvious that the $post_parent property will be 0 on any parent page, so the following idea you would want to run only when $post_parent is not 0

I cannot code anything concrete now, but in short, the basic idea would be:

  • First check the current post parent. If the post parent is not 0, you would want to get the top post parent

  • Once we have established that the current post parent is not 0, we need to use get_ancestors() to return the top most parent post.


    $parent = get_ancestors( 
        get_queried_object_id(), // Get current page ID
        'page' // Post type
    var_dump( $parent );
  • Now that you have an array of parent ID's, you would want to get the top most parent ID from the array. This will always be the last ID in the array, so you would want to

    • a) flip the array (array_flip) to get the top most parent in first place then use $parent[0] to get the top most parent value

    • b) other php functions like end to get the last value in the array

You can now run your code as normal.

  • Thanks Pieter, this did the job! Sorry for the late accept and have a nice weekend! Oct 17, 2015 at 12:57
  • No problem, I'm glad it worked for you. Enjoy the rest of your weekend :-) Oct 17, 2015 at 17:58
  • If anyone is having an issue implementing the solution above the same question was asked and answered here: stackoverflow.com/questions/33155726/…
    – KVDD
    Mar 17, 2020 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.