
I ran into this issue while trying to get the page’s top level parent, no matter who deep the child page was.
Here is the example structure: Parent -> Child -> GrandChild.
And here is the code which lets you get at the Parent name or ID, when you’re on either Child or GrandChild.
You could throw this into your functions.php file if you want to use it in your theme:
function get_top_level_parent_title() {
global $post;
if ( empty($post->post_parent) )
{ the_title(); }
else {
$ancestors = get_post_ancestors($post->ID);
end($ancestors);
echo get_the_title($ancestors[0]);
}
}First use the global $post; to properly get the post data for the current page you’re on.
Secondly, ensure you’re on a page that is not the parent, which is:
if ( empty($post->post_parent))
Thirdly, run through the code after you know you’re on a Child or GrandChild page, using get_post_ancestors(). This function works like a charm. It returns all the pages above it. The function will then return an array, even if it’s just one value, that has the top level parent as the last value.
So then use end() to grab the last value in the array, which is the top level parent.
You’ll then have the ID of the top level parent and if you want to grab the title, use the code above and grab value of the (first and only) item in the array, using [0].
Questions or feedback, leave ‘em in the comments ![]()



Jonathan, I spent a good deal of time looking for such a function. Yours got me close, but as it was written, still returned the immediate parent. I was able to get it to work by combining the last two lines to:
echo get_the_title(end($ancestors));
Your explanation of the code gave me a clue to make this change. Thanks!
Hi Jonathan
Does your code work against this bug ?
http://core.trac.wordpress.org/ticket/10381
From your experience with latest WP (3.2.1) does get_post_ancestors() always work as expected ?
( If both of your answer is yes, then maybe the ticket is already fixed. )
Thanks a lot.
Hey Paul,
I’m not 100% sure if it’s tested against that bug or not, I haven’t had a chance to actually test that.
I’m running 3.2.1 and the code seems to be working just fine for me.
If you get a chance to test it out, please let me know how the tests go.