6

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?

6

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;
3

Here's a solution. It uses the get_ancestors() function, which returns an array of the current page's ancestors from lowest to highest in hierarchy.

Since I didn't really get in which order you wanted to display it (lowest to highest or highest to lowest), I set a $reverse param (default:false) to change the order.

<?php 

function print_page_parents($reverse = false){
  global $post;

  //create array of pages (i.e. current, parent, grandparent)
  $page = array($post->ID);
  $page_ancestors = get_ancestors($post->ID, 'page');
  $pages = array_merge($page, $page_ancestors);

  if($reverse) {
    //reverse array (i.e. grandparent, parent, current)
    $pages = array_reverse($pages);
  }

  for($i=0; $i<count($pages); $i++) {
    $output.= get_the_title($pages[$i]);
    if($i != count($pages) - 1){
      $output.= " &raquo; ";
    }
  }
    echo $output;
}

//print lowest to highest
print_page_parents();

//print highest to lowest
print_page_parents($reverse = true);

?>

I hope it helps!

Vq.

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.