Tag Archives: queries

How to query if is Page, Child of Page, or Grandchild of Page

Say you want to show a certain menu depending on what page you’re on. So if I have in my navigation a link that has Children and Grandchildren, this is how you check to see what page you’re on, if it’s a child or even a Grandchild of a certain page.

Do stuff if is page:

 if (is_page('products') ) {
//Do stuff
} 

Do stuff if is a child of a page: (My products page’s id=17 and I’m viewing, Products > “Cars”)

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

Do stuff if is a Grandchild of a page: (My products page’s id=17 and I’m viewing, Products > Cars > “Red Cars”)

global $post;
$ancs = get_ancestors($post->ID, 'page');
if ($ancs[1] == 17) {
//Do stuff
}

Do stuff if is a Page, or a Child of that page or a Grandchild of that page: (All together now)

global $post;
$ancs = get_ancestors($post->ID, 'page');
if ( $ancs[1] == 17 || $post->post_parent == '17' || is_page('products') ) {
//Do stuff
}