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

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">