WordPress at a glance

get_post_ancestors() WP 1.0

Retrieve ancestors of a post.

Is the basis for: get_ancestors()
Works based on: get_post()

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.

Code of get_post_ancestors: wp-includes/post.php VER 4.9.8

<?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 tag: Relations (of posts terms...)

More from category: Pages

No comments
    Hello, !     Log In . Register