Get Parent page AND top level Parent page

This is the code for the top level parent page

//Get the top level parent page id
function get_top_parent_page_id() {
global $post;
$ancestors = $post->ancestors;

// Check if page is a child page (any level)
if ($ancestors) {
// Grab the ID of top-level page from the tree
return end($ancestors);
} else {
// Page is the top level, so use it’s own id
return $post->ID;
}
}

Put this in your page template and use the $parent_page variable

<?php $parent_page = get_top_parent_page_id($post->ID); echo $parent_page; ?>

 

This is for just the parent of the current page

function get_parent_id() {
global $post; // load details about this page

if ( is_page() && $post->post_parent ) { // test to see if the page has a parent
return $post->post_parent; // return the ID of the parent post

} else { // there is no parent so …
return false; // … the answer to the question is false
}
}

Put this in your page template and use the $parent_page_id variable

<?php $parent_page_id = get_parent_id($post->ID); echo $parent_page_id; ?>

Leave a Reply