page title, parent tilte and grand parent title

I am using a page hierarchy and I want to show the title of the parents and grand parents page (if there is any).

The structure is something like

Startpage

Startpage > Second page

Startpage > Second page > Third page

Startpage > Second page > Third page > Fourth page

The title should be something like
On the Fourth page: “Fourth page – Third page – Second page – Startpage”
On the Third page: “Third page – Second page – Startpage”

The solution I have found isn’t that good:

<title><?php

if(is_page()){

$parent = get_post($post->post_parent);
$parent_title = get_the_title($parent);
$grandparent = $parent->post_parent;
$grandparent_title = get_the_title($grandparent);
    if ($parent) {
        if ($grandparent) {
            echo wp_title('') . " - " . $parent_title . " - " . $grandparent_title . " - ";
        }
        else {
            echo wp_title('') . " - " . $parent_title . " - ";  
        }
    }

    else {
        echo wp_title('') . " - ";
    }
}?>  Startpage</title>

On the Second page level the title for that page gets double… “Second page – Second page – Start page”

Anyone?

2 s
2

possibly build on get_ancestors();

example:

if( is_page() ) :
    echo $post->post_title;
    if( $ancs = get_ancestors($post->ID,'page') ) {
        foreach( $ancs as $anc ) {
        echo ' -> ' . get_page( $anc )->post_title;
        }
    }   
endif;

Leave a Comment