6

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?

13

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.

  • 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. – Chip Bennett Oct 25 '11 at 15:09
  • Hope you don't mind the edit. (+1) – kaiser Oct 25 '11 at 17:55
4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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