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

时间:2012-12-17 15:14:59

标签: php wordpress

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

我的页面设置如下:

- 家长

----儿童第1页

----儿童第2页

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

我知道我可以做类似下面的事情,但我想在不包含特定页面ID的情况下使其更具动态性。

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

4 个答案:

答案 0 :(得分:53)

您可以测试帖子是否是这样的子页面:
*(来自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
}
?>

答案 1 :(得分:4)

将此功能放在主题的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
};

然后你可以使用它:

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

答案 2 :(得分:4)

我知道这是一个老问题,但我在寻找同样的问题,在找到这个问题之前,我找不到清晰简单的答案。我的回答并没有回答他的解释,但它回答了我正在寻找的主要问题。

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

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

答案 3 :(得分:0)

对于Wordpress,您只需检查以下内容即可:

<?php 
  if (wp_get_post_parent_id(get_the_ID())) {
    echo "I am a child page";
  } 
?>
相关问题