Get top level page parent title

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

Let me describe:

Read More

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?

Related posts

Leave a Reply

2 comments

  1. 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.

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