There are some issues in your code, e.g. $pages
will always return an array, even where there are no results in which an empty array is returned, so if ( is_page() && $pages ) return true;
does not necessarily mean that “we’re at the page or at a sub page“. Instead, it means, “as long as it’s a Page (post type page
), then we return true”.
Nonetheless, try the following which works even if the page in question has a grandchild:
// This function checks whether the current Page has the specified ID ($pid), or
// that the current Page is a direct or indirect child of $pid.
function is_tree( $pid ) {
// ID of the specific child page that you want to exclude.
$cid = 4419;
// Bail early if we're not on a Page.
if ( ! is_page() ) {
return false;
}
$page_id = get_queried_object_id();
$pid = (int) $pid;
// We're on the parent page.
if ( $pid === $page_id ) {
return true;
}
// We're on the **excluded child page**, so return false.
if ( (int) $cid === $page_id ) {
return false;
}
$pages = get_pages( array( 'child_of' => $pid ) );
// Check if we're on one of the other child pages.
return in_array( $page_id, wp_list_pluck( $pages, 'ID' ) );
}