7

How do I get the page title of the upper most parent page of the page the visitor is currently on?

Let me describe:

I have this page structure:

  • Example Title 1
    • Example Title 1-1
      • Example Title 1-1-1
      • Example Title 1-1-2
    • Example Title 1-2
  • Example Title 2
  • Example Title 3
  • Example Title 4

Here is what I want to return:

  • User is on Example Title 1 return Example Title 1
  • User is on Example Title 1-1 return Example Title 1
  • User is on Example Title 1-1-1 return Example Title 1
  • User is on Example Title 2 return Example Title 2

Normally what I would do is check $post->parent and if 0 then return page title else return title of page above. Problem is that $post->parent will only go back one level. I need to use some sort of recursive function that keeps going back until $post->parent == 0.

Now I can manage this myself but the only way I could think of doing it would be to use get_post() each time but imagine I'm 8 layers deep (we need to go deeper). That would involve loading 8 pages to finally get to the top level. Anyone have a better way to do this?

2 Answers 2

15

Found this way:

if ( 0 == $post->post_parent ) {
    the_title();
} else {
    $parents = get_post_ancestors( $post->ID );
    echo apply_filters( "the_title", get_the_title( end ( $parents ) ) );
}

Anyone got a better way please answer.

3
  • That's probably about as good as any. One other way would be to loop iteratively through get_page( array( 'post_parent' => $post->post_parent ) ) until you get to the top of the hierarchy. Your approach would clearly be more efficient. Commented Oct 25, 2011 at 15:09
  • Hope you don't mind the edit. (+1)
    – kaiser
    Commented Oct 25, 2011 at 17:55
  • I know this is old, but as it provides an array (even if there's only one ancestor), doesn't seem to work.
    – Nathan
    Commented Oct 14, 2022 at 17:23
5

Not sure if its the efficient this can be done via recursive function

function get_post_ancestor_title($post_id){
    $post = get_post($post_id)->post_parent;
    if ( 0 == $post->post_parent ) {
       return get_the_title();
    } else {
       get_post_ancestor_title($post->ID);
    }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.