get_post_ancestors() WordPress Function

The get_post_ancestors() function is used to retrieve the ancestors of a post. This function returns an array of ancestor IDs, with the oldest ancestor being the first element and the immediate parent being the last element.

get_post_ancestors( int|WP_Post $post ) #

Retrieves the IDs of the ancestors of a post.


Parameters

$post

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


Top ↑

Return

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


Top ↑

Source

File: wp-includes/post.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          = $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
VersionDescription
2.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More