问题描述

我有一个默认页面模板,我想用于两种情况。为了简化我的客户,我宁愿只使用一个页面模板。

这是我要完成的:

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 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。