get_post_ancestors( int|WP_Post $post ): int[]

Retrieves the IDs of the ancestors of a post.

Parameters

$postint|WP_Postrequired
Post ID or post object.

Return

int[] Array of ancestor IDs or empty array if there are none.

Source

function get_post_ancestors( $post ) {
	$post = get_post( $post );

	if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID ) {
		return array();
	}

	$ancestors = array();

	$id          = $post->post_parent;
	$ancestors[] = $id;

	while ( $ancestor = get_post( $id ) ) {
		// Loop detection: If the ancestor has been seen before, break.
		if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors, true ) ) {
			break;
		}

		$id          = $ancestor->post_parent;
		$ancestors[] = $id;
	}

	return $ancestors;
}

Changelog

VersionDescription
2.5.0Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Get Ancestors Page Thumbnail
    Get the top level page thumbnail and display it!

    <?php
    global $post;
    $parents = get_post_ancestors( $post );
    $id = $post->ID;
    /* Get the ID of the 'top most' Page */
    if ( ! empty( $parents ) ) {
        $id = array_pop( $parents );
    }
    if ( has_post_thumbnail( $id ) ) {
        echo get_the_post_thumbnail( $id, 'thumbnail' );
    }
    ?>
  2. Skip to note 5 content

    Get Ancestors Page Slug
    This example returns the highest page {slug} in a tree and uses it as a Body_Class, so the parent and all children will have the same Body Class!

    This example for a twenty eleven child theme in the header.php file

    </head>
    
    <?php
    /* Get the Page Slug to Use as a Body Class, this will only return a value on pages! */
    $class = '';
    /* is it a page */
    if( is_page() ) { 
    	global $post;
    	/* Get an array of Ancestors and Parents if they exist */
    	$parents = get_post_ancestors( $post->ID );
    	/* Get the top Level page->ID count base 1, array base 0 so -1 */ 
    	$id = ($parents) ? $parents[count($parents)-1]: $post->ID;
    	/* Get the parent and set the $class with the page slug (post_name) */
    	$parent = get_post( $id );
    	$class = $parent->post_name;
    }
    ?>
    
    <body <?php body_class( $class ); ?>>
  3. Skip to note 6 content

    Get Ancestors Post Meta
    If we did not want to use the page slug, we could use a custom field eg: body_class, on the top level page and set the class in the post meta.

    </head>
    
    <?php
    $class = '';
    if( is_page() ) {
    	global $post;
    	$parents = get_post_ancestors( $post->ID );
    	$id = ($parents) ? $parents[count($parents)-1]: $post->ID;
    	$class = get_post_meta( $id, 'body_class', true );
    }
    ?>
    
    <body <?php body_class( $class ); ?>>

You must log in before being able to contribute a note or feedback.