Find ID of Top-Most Parent Page

A deep number of page levels in a website can make navigation difficult for front end users. In addition to breadcrumbs, it is worthwhile to maintain your Top-Most Page Title in all areas to help your visitors find their way between the hierarchical sections of your site.

Nested child pages greater than two levels deep will not work with Page Titles: Ancestor, Parent, Current and Defaults, discussed previously. For hierarchies three levels and greater, you will need the below example to grab the ID of the top-most page.

Original example from CSS-Tricks:

<?php

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

?>

Example with Top-Most Page Title:

global $post;

$ancestors=get_post_ancestors($post->ID);
$root=count($ancestors)-1;
$parent = $ancestors[$root];


if ($post->post_parent) { ?>

	<h1 class="entry-title"><?php echo get_the_title($parent); ?></h1>

<?php } else { ?>

	<h1 class="entry-title"><?php the_title(); ?></h1>

<?php } ?>

Example with Top-Most Page Title and ACF Field:

global $post;

$ancestors=get_post_ancestors($post->ID);
$root=count($ancestors)-1;
$parent = $ancestors[$root];


if ($post->post_parent) { ?>

	<h1 class="entry-title"><?php 
		if (get_field('alternate_title', $parent)) {
			the_field('alternate_title', $parent);
		} else {
			echo get_the_title($parent); 
		}
	?></h1>

<?php } else { ?>

	<h1 class="entry-title"><?php 
		if (get_field('alternate_title')) {
			the_field('alternate_title');
		} else {
			echo get_the_title(); 
		}
	?></h1>

<?php } ?>

Alternate method with current, parent and grandparent:

$currentpage = $post->ID; // current page id
$parentpage = $post->post_parent; // all parents and grand parents
$grandparent = get_post_ancestors($currentpage); // grand parent page id
$grandparentID = $grandparent[1]; // grandparent with first item in array selected

Source.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.