Useful functions for checking Pages and their sub Pages in WordPress

Posted on
5/5 - (446 votes)

To check a Page by ID for that Page or its direct descendants (sub/child pages)

// To check a Page by ID for that Page or its direct descendants (sub/child pages)
function is_tree( $pid ) { // $pid = The ID of the page we're looking for pages underneath

	global $post; // load details about this page

	if( is_page() && ( $post->post_parent == $pid || is_page( $pid ) ) )
		return true; // we're at the page or at a sub page
	else
		return false; // we're elsewhere

}

Usage: if ( is_tree( 645 ) ) {}

or to check by ID or slug or title:

/**
*   Child page conditional
*   @ Accept's page ID, page slug or page title as parameters
*/
function is_child( $parent = '' ) {
	global $post;

	$parent_obj = get_page( $post->post_parent, ARRAY_A );
	$parent = (string) $parent;
	$parent_array = (array) $parent;

	if ( in_array( (string) $parent_obj['ID'], $parent_array ) ) {
		return true;
	} elseif ( in_array( (string) $parent_obj['post_title'], $parent_array ) ) {
		return true;
	} elseif ( in_array( (string) $parent_obj['post_name'], $parent_array ) ) {
		return true;
	} else {
		return false;
	}
}

Usage:

if ( is_child( 645 ) ) {} or if ( is_child( 'Services' ) ) {} or if ( is_child( 'our-services' ) ) {}

To check a Page by ID for that Page or any/all of its child pages (incl. grandchildren)

// To check a Page by ID and all its child Pages incl. grand children
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 check a Page by ID if it is an ancestor

function is_ancestor( $post_id ) {

	global $wp_query;

	$ancestors = $wp_query->post->ancestors;

	if ( in_array( $post_id, $ancestors ) ) {
		$return = true;
	} else {
		$return = false;
	}
	
	return $return;
}