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.
Return
(int[]) Array of ancestor IDs or empty array if there are none.
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; }
Expand full source codeCollapse full source codeView on TracView on GitHub
Changelog
Version | Description |
---|---|
2.5.0 | Introduced. |