Example:
- Root parent page (we need to get the id of this page)
- Subpage
- Sub-subpage
- Sub-sub-subpage (we are here)
- Sub-subpage
- Subpage
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); ?>