Get parent page on the root level

We have next structure: Page=Subpage=Subsubpage=Subsubsubpage. We are on "Subsubsubpage" and we want to get parent page on the root level of current page.

Add this code to functions.php file:


<?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);

}

?>

Add this code to template file:


<?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>

Leave a Comment