is_tree conditional extended: finding WordPress child/grandchild pages by ID or slug

WordPress has some handy conditional functions (conditional tags as stated on WP Developers Theme Handbook), such as is_post, is_home and is_page. Unfortunatelly, is_page doesn't find child and grandchild pages.

Luckily, if you search for help around the interwebz you will find is_tree, a function that finds child and grandchild pages. It's even mentioned on Developer Handbook, which makes me wonder why is not in WP core yet.

is_tree conditional - extended version

For a while, I've been using is_tree conditional in a extended version which allows the use of page slugs, and not only IDs. It's available on Github.

/**
 * is_tree extended function.
 * 
 * Extends the typical is_tree function -- as found in WordPress Theme Handbook ( https://developer.wordpress.org/themes/basics/conditional-tags/ ) and CSS Tricks ( https://css-tricks.com/snippets/wordpress/if-page-is-parent-or-child/ ) -- and allows it to find if a page is child or grandchild of another page by it's slug
 * 
 * @access public
 * @author Celso Bessa <>
 * @see https://celsobessa.com.br/is-tree-conditional-extended/
 * @param mixed $page
 * @param bool $use_slug if set to true, (default: false)
 * @return bool true if a page is child or grandchild of another page
 */
function is_tree( $page_id, $use_slug = false ) {
	
	if ( $use_slug === true && !is_string( $page_id ) ) {
		return false;
	} else if ( $use_slug !== true && !is_int( $page_id ) ) {
		return false;
	}
	
	if ( $use_slug === true ) {
		$page_data = get_page_by_path( $page_id );
		if ( null === $page_data ) {
			return false;
		}
		$page_id = $page_data->ID;
	}
	
	global $post;         // load details about this page
	if( is_page( $page_id ) ) {
		return true;   // we're at the page or at a sub page
	}
 
    $anc = get_post_ancestors( $post->ID );
    foreach ( $anc as $ancestor ) {
        if( is_page() && $ancestor == $page_id ) {
            return true;
        }
    }
		
	return false;  // we're elsewhere

};

Hope it helps.