Using WordPress conditional tags can be quite helpful when working within plugins or themes. For instance, within the loop, you might want to know if you are dealing with a specific page:
if ( is_page(13) ) { //do some stuff to page with id of 13 }
Pretty simple and everyone knows this. But what if I want to know if I am dealing with a child of page 13? Also pretty easy:
if ( $post->post_parent == 13 ) { //do some stuff to a direct child of page 13 }
Combine both to check if we are dealing with either page 13 or a child of page 13:
if ( is_page(13) || $post->post_parent == 13 ) { //do some stuff to page 13 or children of page 13 }
But I want to go one step further! What if I want to know if I am dealing with a child of a child of page 13? And I don’t care how many levels deep, so it could be a child of a child of a child…
This is what you could use:
if ( in_array(13, $post->ancestors) ) { //do some stuff to a child of page 13 (any level deep) }
(Obviously, this will also return true for direct children of page 13)
Now, let’s combine all this together into a useful helper function:
function is_page_downstream($id) { global $post; if (!is_page()) return false; return is_page($id) || in_array($id, $post->ancestors); }
An example
Working with the below page structure, I want to know when I am on page ‘Top Level’ or any downstream page underneath ‘Top Level’, no matter how deep the level of nesting.
is_page_downstream(63) will return true for all pages with id in (63, 65, 76, 78, 67, 81, 84)
And it will return false for pages with id in (23, 27)
Notes & Credit
Please note this was tested on WordPress 3.3.1. Also, credit must go to this post on CSS Tricks for helping me put this post together.