If Page Is Parent or Child

Avatar of Chris Coyier
Chris Coyier on

There are built in conditional WordPress functions for testing for a page:

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

Or for testing if a page is a child of a certain page:

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

But there is no built in function that combines these two things, which is a fairly common need. For example, loading a special CSS page for a whole “branch” of content. Like a “videos” page and all its children individual videos pages.

This function (add to functions.php file) creates new logical function to be used in this way:

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
};

Usage

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