WordPress is_child() for Advanced Navigation
- Share /
- Development, Wordpress / / 8 Comments
WordPress lacks one key feature for advanced developers using it as a CMS platform. That feature is the is_child() (or would be) function. If your familiar with WordPress Theme Development you have probably ran into the following Conditional Tags from time to time:
- is_home()
- is_front_page()
- is_single()
- is_sticky()
- is_page()
If you ever want to have a sidebar navigation display the next level of child pages, you would need is_child() to do so.
// is_child() function is_child($parent) { global $wp_query; if ($wp_query->post->post_parent == $parent) { $return = true; } else { $return = false; } return $return; }
Usage
To use the conditional in your theme(s), add the code above to functions.php. This only takes the Post IDas an argument, so you’ll need to use something like is_child(201); because is_child(‘Services’); will not work.
Working Example
The inner Services pages on kevinleary.net use this function to create a dynamic breadcrumb. I know there are plugins for this but I was looking for something simple and quick.
<?php if(is_child(221)) { ?> <h1 class="post-title"><a href="/services/">Services</a> <em>></em> <?php the_title(); ?></h1> <?php } else { ?> <h1 class="post-title"><?php the_title(); ?></h1> <?php } ?>
Special thanks goes out to Nicholas Roussos for creating this wonderful gem.
is_ancestor() function for deeper functionality
<?php function is_ancestor($post_id) { global $wp_query; $ancestors = $wp_query->post->ancestors; if ( in_array($post_id, $ancestors) ) { $return = true; } else { $return = false; } return $return; } ?>
By popular demand, I’ve added a more in depth way to check if a post is a child OR an ancestor of a specific page ID. This hasn’t been tested yet, if it doesn’t work let me know and I can fix it.


JTL / 5.19.09 / 2:39 PM
try copy and paste again buddy — your code is chalk full o errors!
kevin / 5.20.09 / 6:27 AM
All fixed, looks like I forgot to add the opening and closing PHP tags.
Natawa / 7.17.09 / 11:42 AM
Прив, Ваш сайт прикольный хотела узнать на каком движке делали? и смогу ли я что-то подобное сделать на Ворд Пресе?
Anton / 7.27.09 / 11:39 AM
Как узнать пароль , если раньше был у Вас на сайте зарегестрирован?
Katya / 7.28.09 / 6:58 AM
Ребята, привет, а реально такой сайт как у Вас написать в штмл?. у меня знание посредственные..
kevinlearynet / 7.28.09 / 12:02 PM
Sorry Natawa, I’m an english only kind of guy. What language is that?
I’ll see if I can have it or possibly the site auto translated for you.
Olegreze / 9.9.09 / 3:59 PM
Основная задача Яндекса — давать ответы на вопросы пользователей!
Петрович / 11.28.09 / 7:55 AM
Впечатлило, однако!