Wordpress: Is_Child Function

Here’s a handy WordPress function I put together today. It tells you if the current page is a child of another page. I’m using it to show a sub-navigation on a page and its children.

function is_child ($parent) {
global $wp_query;
if ($wp_query->post->post_parent == $parent) {
$return = true;
}
else {
$return = false;
}
return $return;
}

4 Responses to “Wordpress: Is_Child Function”

  1. mIKE Says:

    Could this be used in an if statement to not display child pages?

    ex:

    if(is_child(’parentpageidhere’))

    I’m looking for something that will not display child pages if you are currently on a child page of a specific parent page.

  2. Nicholas Roussos Says:

    if you didn’t want to display child pages, you could simply say:

    if (!is_child(’parentpageid’)) {
    //code here
    }

    The key thing is ! (not) tells you to only do the code when is_child returns false.

  3. mIKE Says:

    Thanks!

    I’ve been looking for something like this all day :S, and this function works great!

    And thanks for responding so quickly.. 3 minutes.

    Kudos Nicholas!

  4. Nicholas Roussos Says:

    No problem Mike. I just realized that this function will only detect direct children and not grandchildren (if that makes sense). Basically, you can have a page that’s a child of a child of a child. Anyway,I might fix that in the future, but it will only complicate it. The function would probably need to be recursive or something …