php 检查页面是父页面还是子页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13916783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:15:26  来源:igfitidea点击:

Check if a page is a parent or if it's a child page?

phpwordpress

提问by Rob

Is it possible to check if a page is a parent or if it's a child page?

是否可以检查页面是父页面还是子页面?

I have my pages set up like this:

我的页面设置如下:

-- Parent

-- 家长

---- Child page 1

---- 子页面 1

---- Child page 2

---- 子页面 2

etc.

等等。

I want to show a certain menu if it's a parent page and a different menu if it's on the child page.

如果它是父页面,我想显示某个菜单,如果它在子页面上,我想显示一个不同的菜单。

I know I can do something like below but I want to make it a bit more dynamic without including specific page ID's.

我知道我可以做类似下面的事情,但我想让它更加动态而不包含特定的页面 ID。

<?php
if ($post->post_parent == '100') { // if current page is child of page with page ID 100
   // show image X 
}
?>

回答by Alex

You can test if the post is a subpage like this:
*(from http://codex.wordpress.org/Conditional_Tags)*

您可以测试帖子是否是这样的子页面:
*(来自http://codex.wordpress.org/Conditional_Tags)*

<?php

global $post;     // if outside the loop

if ( is_page() && $post->post_parent ) {
    // This is a subpage

} else {
    // This is not a subpage
}
?>

回答by Matthew T Rader

I know this is an old question but I was searching for this same question and couldn't find a clear and simple answer until I came up with this one. My answer doesn't answer his explanation but it answers the main question which is what I was looking for.

我知道这是一个老问题,但我一直在寻找同样的问题,直到我想出这个问题才找到一个清晰而简单的答案。我的回答没有回答他的解释,但它回答了我一直在寻找的主要问题。

This checks whether a page is a child or a parent and allows you to show, for example a sidebar menu, only on pages that are either a child or a parent and not on pages that do not have a parent nor children.

这会检查页面是子页面还是父页面,并允许您仅在子页面或父页面上显示,例如侧边栏菜单,而不是在没有父页面或子页面的页面上显示。

<?php 
   global $post;    
   $children = get_pages( array( 'child_of' => $post->ID ) );
   if ( is_page() && ($post->post_parent || count( $children ) > 0  )) : 
?>

回答by Queli Coto

Put this function in the functions.php file of your theme.

把这个函数放在你的主题的functions.php 文件中。

function is_page_child($pid) {// $pid = The ID of the page we're looking for pages underneath
  global $post;         // load details about this page
  $anc = get_post_ancestors( $post->ID );
  foreach($anc as $ancestor) {
      if(is_page() && $ancestor == $pid) {
          return true;
      }
  }
  if(is_page()&&(is_page($pid)))
     return true;   // we're at the page or at a sub page
  else
      return false;  // we're elsewhere
};

Then you can use it:

然后你可以使用它:

<?php 
    if(is_page_child(100)) {
        // show image X 
    } 
?>