get_post_ancestors() – Retrieve ancestors of a post.

You appear to be a bot. Output may be restricted

Description

Retrieves the IDs of the ancestors of a post.

Usage

$int[] = get_post_ancestors( $post );

Parameters

$post
( int|WP_Post ) required – Post ID or post object.

Returns

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

Source

File name: wordpress/wp-includes/post.php
Lines:

1 to 24 of 24
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;
}
 

 View on GitHub View on Trac