如果页面是父级或子级

Avatar of Chris Coyier
Chris Coyier

WordPress 有内置的条件函数,用于测试页面

if ( is_page(2) ) {
  // stuff
}

或测试页面是否为某个页面的子页面

if ( $post->post_parent == '2' ) {
  // stuff
}

但没有内置函数可以将这两者结合起来,而这是一种相当常见的需求。例如,为整个内容“分支”加载一个特殊的 CSS 页面。例如,一个“视频”页面及其所有子视频页面。

此函数(添加到 functions.php 文件)创建了新的逻辑函数,可以以这种方式使用

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

用法

if (is_tree(2)) {
   // stuff
}