Blog

Check if Current Page is in Tree

Tutorials, Wordpress, WordPress Tutorials4 comments

This is a really useful little snippet I found in the WordPress Codex. It allows us to check whether a page is within a specified tree, e.g. whether a page is a certain ID or if it is a subpage of that ID.

Here’s the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function is_tree($pid)
{
	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 we can perform the check from within the WordPress loop like this:

1
2
3
4
if ( is_tree('4') )
	{
		// run this code
	}

The above snippet will check if the current page has an ID of 4 or if a parent of the current page has an ID of 4. If the check comes back true, the code within the brackets will be run.

4 Comments
  1. weblogguide says:

    Can you show me on picture how this code will be work?

  2. Think of it like this:

    Top Level Parent Page with ID of 248

    1. Sub Page 1
    2. sub page 2
      • Sub 1 of subpage 2

    So you have the tree of pages as outlined above, and you want to be able to check whether Sub 1 of Subpage 2 is actually somewhere in the tree, or, in other words, check to make sure that the page with an ID of 248 is the parent of the parent.

    That’s what this is for.

  3. Rahul says:

    How can I check current page is home page or other.

    I try this syntax

    if ( is_home() ) { echo ‘ class=”current_page_item”‘; }

    But not working I use wordpress 3.3

    Any idea…???

  4. is_home() actually refers to the blog page. Use is_front_page() to detect if on the home page.

Leave a Reply