get_post_ancestors() WP 1.0
Retrieve ancestors of a post.
✈ 1 time = 0.001242s = very slow | 50000 times = 0.33s = very fast | PHP 7.2.5, WP 5.0.1
No Hooks.
Return
Array. Ancestor IDs or empty array if none are found.
Usage
get_post_ancestors( $post );
- $post(int/WP_Post) (required)
- Post ID or post object.
<?php
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 = $ancestors[] = $post->post_parent;
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 ) )
break;
$id = $ancestors[] = $ancestor->post_parent;
}
return $ancestors;
}
Related Functions
From tag: post
More from category: Pages