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 . " &lsaquo; ";
    		}
    		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?