問題描述

我有一個默認頁面模板,我想用於兩種情況。為了簡化我的客户,我寧願只使用一個頁面模板。

這是我要完成的:

if parent_page OR if child-page without children {
  display full-width-layout
}
if child page with children or if grandchild page {
  display sidebar-menu-layout
}

這可能嗎?

這是我迄今為止所嘗試過的

if( is_page() && $post->post_parent > 0 ) {
  //display sidebar-menu-layout
} else {
  //display full-width-layout
}

它可以在頂級頁面上工作,它顯示 full-width-layouts 。但是,我可以做些什麼來確保 sidebar-menu-layout 與 child-pages 一起顯示在兒童和僅在孫子頁面上?而對於沒有孩子的 child-pages,要顯示 full-width-layout 。

提前致謝。我相信它有一個簡單的解決方案,我只是相對較新的 WP,所以仍然試圖找出什麼可以和不能做。

最佳解決方案

在閲讀解決方案之前,Bravokeyl 已經提供了一個可以為我工作的解決方案。我不知道哪個是更好的兩個,或最正確的,我只知道我為我工作,為我的問題。

這是我用來顯示 full-width 佈局或 sidebar-menu 佈局的代碼:

if( is_page() && $post->post_parent > 0 ) {
  // post has parents

  $children = get_pages('child_of='.$post->ID);
  if( count( $children ) != 0 ) {
    // display sidebar-menu layout
  }

  $parent = get_post_ancestors($post->ID);
  if( count( $children ) <= 0  && empty($parent[1]) ) {
    // display full-width layout
  } elseif ( count( $children ) <= 0  && !empty($parent[1]) )  {
    // display sidebar-menu layout
  }

} else {
  // post has no parents
  // display full-width layout
}

次佳解決方案

Level-0
--Level-1
----Level-2
------Level-3
----Levelanother-2
--Levelanother-1

檢查頁面是否是頂級頁面 (可能還有孩子)?

$post->$post_parent == 0 或為空 get_post_ancestors( $post )僅返回 0 級頁面。

是子頁面,是 Level-1 頁面還是 Levelanother-1?

$post->$post_parent > 0 或不為空 get_post_ancestors( $post )為空 get_post_ancestors( $post->post_parent )

是 level-1 頁面,但沒有像 Levelanother-1 頁面的孩子?

$post->$post_parent > 0 或不為空 get_post_ancestors( $post ),為空 get_post_ancestors( $post->post_parent )count(get_children( $post ->ID, 'ARRAY_A' )) == 0 ..

我沒有檢查這個,但它應該工作正常。您也可以使用 get_page_children() 和 get_posts()

參考文獻

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