get_post_ancestors()

You are here:

get_post_ancestors( int|WP_Post $post )

Retrieve ancestors of a post.

Parameters Parameters

$post

(int|WP_Post) (Required) Post ID or post object.


Top ↑

Return Return

(int[]) Ancestor IDs or empty array if none are found.


Top ↑

Source Source

File: wp-includes/post.php

806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
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;
}


Top ↑

Changelog Changelog

Changelog
Version Description
2.5.0 Introduced.
Was this article helpful?
Dislike 0
Views: 15