I’m trying to create a simple function to do a “status test”. Goal is to test and see if the current page being viewed has any child pages or not. Using this to alter layout to accomodate child pages. The following code seems like it should work, but alas, no dice.

Anyone see what I’m missing?

function is_subpage() {
global $post;                              // load details about this page

if ( is_page() && $post->post_parent ) {   // test to see if the page has a parent
    return true;                                            // return true, confirming there is a parent

} else {                                   // there is no parent so ...
    return false;                          // ... the answer to the question is false
}

}

2 s
2

Your above function tests whether a page is a child page of some other page, not whether it has children.

You can test for children of the current page like so:

function has_children() {
    global $post;

    $children = get_pages( array( 'child_of' => $post->ID ) );
    if( count( $children ) == 0 ) {
        return false;
    } else {
        return true;
    }
}

Further reading:

  • wp codex: get_pages
  • php manual: count

Leave a Reply

Your email address will not be published. Required fields are marked *