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.
/**
* Child page conditional
* @ Accept's page ID, page slug or page title as parameters
*/
function is_child( $parent = '' ) {
global $post;
$parent_obj = get_page( $post->post_parent, ARRAY_A );
$parent = (string) $parent;
$parent_array = (array) $parent;
if ( in_array( (string) $parent_obj['ID'], $parent_array ) ) {
return true;
} elseif ( in_array( (string) $parent_obj['post_title'], $parent_array ) ) {
return true;
} elseif ( in_array( (string) $parent_obj['post_name'], $parent_array ) ) {
return true;
} else {
return false;
}
}
To use the conditional in your theme(s), add the code above to functions.php
. This function now takes the a Post ID, post slug or post title as an argument, so you can use any of the following options:
is_child(201)
is_child('Services')
is_child('our-services')
<?php if( is_child(221) ): ?>
<a href="<?php echo get_permalink(221); ?>">Services</a> > <?php the_title(); ?>
<?php else: ?>
<?php the_title(); ?>
<?php endif; ?>
For deeper page tree’s, this is_ancestor()
function works well.
<?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.