問題描述

我正在使用頁面層次結構,我想顯示父母和父母頁面的標題 (如果有的話) 。

結構就是這樣

首頁

起始頁> 第二頁

起始頁> 第二頁> 第三頁

起始頁> 第二頁> 第三頁> 第四頁

標題應該是第四頁:「第四頁 – 第三頁 – 第二頁 – 開始」 第三頁:「第三頁 – 第二頁 – 開始」

我發現的解決方案不是那麼好:

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

在第二頁級別,該頁面的標題獲得雙倍…「第二頁 – 第二頁 – 起始頁」

任何人?

最佳解決思路

可能建立在 get_ancestors()上;

例:

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;

次佳解決思路

這是一個解決方案。它使用 get_ancestors()函式,該函式將當前頁面的祖先的陣列從最低層次返回到最高層。

由於我沒有真正按照你想顯示的順序 (從最低到最高或最高到最低),我設定了一個 $ reverse param(預設值:false) 來更改順序。

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

?>

我希望它有幫助!

VQ 。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。