Get the id of the parent page on the root level

Example:

  • Root parent page (we need to get the id of this page)
    • Subpage
      • Sub-subpage
        • Sub-sub-subpage (we are here)

Recursive function for getting parent page id on root level in functions.php. Works with any nesting depth:

<?php
function get_root_parent_id( $page_id ) {
	global $wpdb;
	$parent = $wpdb->get_var( "SELECT post_parent FROM $wpdb->posts WHERE post_type='page' AND post_status='publish' AND ID = '$page_id'" );
	if( $parent == 0 ) {
		return $page_id;
	} else {
		return get_root_parent_id( $parent );
	}
}
?>

Usage in template:

<?php
global $post;
$page_id = $post->ID;
$root_parent_id = get_root_parent_id( $page_id );
?>

Another way with native WordPress solution:

<?php
if ( $post->post_parent ) {
	$ancestors = get_post_ancestors( $post->ID );
	$root = count( $ancestors ) - 1;
	$parent = $ancestors[$root];
} else {
	$parent = $post->ID;
}
?>

Another example:

<?php
global $post;
$page_id = $post->ID;
//Here is the Root Parent page
$root_parent_id = get_root_parent_id($page_id);
$root_parent_page = get_post($root_parent_id);
//Here is the page title
$root_parent_title = $root_parent_page->post_title;
//Here is the page link
$root_parent_link = get_permalink($root_parent_id);
?>
<h3><a href="<?php echo $root_parent_link;?>" title="<?php echo $root_parent_title;?>"><?php echo $root_parent_title;?></a></h3>
<ul class="sidebar_menu">
	<?php wp_list_pages("title_li=&child_of=$root_parent_id"); ?>
</ul>

2 comments on “Get the id of the parent page on the root level

  1. Thanks, made my day!

    Any tips how to include the root page featured image?
    Meaning I want to display the Root page title and display its featured image (a country flag) in front of it.

Leave a Reply

Your email address will not be published. Required fields are marked *