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()
✈ 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.

Changelog

Since 2.5.0 Introduced.

Code of get post ancestors: wp-includes/post.php WP 5.2.4

<?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