get_post_ancestors( int|WP_Post $post ): int[]
Retrieves the IDs of the ancestors of a post.
Parameters
-
$post
int|WP_Post Required -
Post ID or post object.
Return
int[] Array of ancestor IDs or empty array if there are none.
Source
File: wp-includes/post.php
.
View all references
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
Version | Description |
---|---|
2.5.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Get Ancestors Page Thumbnail
Get the top level page thumbnail and display it!
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
fileGet 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.