How can I detect hierarchal relationships beyond children (grandchild, great-grandchild, etc)?

Often times, a custom theme for WordPress will require a dynamic content that reflects a relationship to a top level page of a site.

Is there a Conditional Tag that will check if the current page is a grand-child (or separated by further generations) by ID?

Related posts

Leave a Reply

1 comment

  1. Turns out there is an excellent function that has been passed around the WordPress forums is_tree()

    function is_tree($pid) {      // $pid = The ID of the page we're looking for pages underneath
        global $post;         // load details about this page
    
        $anc = get_post_ancestors( $post->ID );
        foreach($anc as $ancestor) {
            if(is_page() && $ancestor == $pid) {
                return true;
            }
        }
        if(is_page()&&(is_page($pid))) 
                   return true;   // we're at the page or at a sub page
        else 
                   return false;  // we're elsewhere
    };
    

    To use it in template, just give it the ID you want to check the current page against, and it will return true if the current page is a descendant.

    <?php if(is_tree(12)){echo 'foobar';} ?>