Keep page hierarchy in wp_list_pages, even if on a child or grandchild

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.

    Example

    $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.