After you global $post
, you can use the core WordPress function get_post_ancestors()
to retrieve the parent pages.
Example
$ancestors = get_post_ancestors($post);
if($ancestors){
foreach(array_reverse($ancestors) as $post_id){
$ancestor_page = get_post($post_id);
}
}
Then, to retrieve all child pages of the current page, you could make it easy by using a custom function. Place your custom function in your currently active theme functions.php
file.
Example
if(!function_exists('mbe_get_post_children')){
function mbe_get_post_children($object){
$data = array();
$query = new WP_Query(array(
'posts_per_page' => '-1',
'post_type' => $object->post_type,
'post_status' => 'publish',
'post_parent' => $object->ID
));
wp_reset_query();
wp_reset_postdata();
if(!$query->posts){
return false;
}
foreach($query->posts as $child_post){
$data[] = $child_post;
if($child_post->post_parent != $object->ID && $child_post->post_parent != 0){
mbe_get_post_children($child_post);
}
}
return $data;
}
}
Then to use your custom function which retrieves all child pages of the current page, would be something very similar to the first example, which retrieves all parent pages of the current page.
Example
if(function_exists('mbe_get_post_children')){
$children = mbe_get_post_children($post);
if($children){
foreach($children as $child_id){
$child_page = get_post($child_id);
}
}
}