You can use this code to find the absolute parent for any page:
// Get the current page object
$page = get_queried_object();
// Check if the current page has a parent
if ( $page->post_parent ) {
// Set the parent ID to the current page's parent ID
$parent_id = $page->post_parent;
} else {
// Set the parent ID to the current page's ID
$parent_id = $page->ID;
}
// Loop through the ancestors of the current page
while ( $parent_id ) {
// Get the parent page object
$parent = get_page( $parent_id );
// Check if the parent page has a parent
if ( $parent->post_parent ) {
// Set the parent ID to the parent page's parent ID
$parent_id = $parent->post_parent;
} else {
// Set the parent ID to 0 to exit the loop
$parent_id = 0;
}
}
// The absolute parent page is now stored in the $parent variable
The code starts by getting the current page object using the ‘get_queried_object’ function. Then, it checks if the current page has a parent using the ‘post_parent’ property of the page object. If the current page has a parent, the parent ID is set to the current page’s parent ID. If the current page does not have a parent, the parent ID is set to the current page’s ID.
Next, the code enters a loop which runs until the parent ID is set to 0. Inside the loop, the parent page object is retrieved using the ‘get_page’ function, and the parent ID is updated based on whether the parent page has a parent or not.