Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get the top most parent of a WordPress post
/**
* Gets the top most ancestor for a post.
*
* @param object $post The current post
*
* @return integer The post ID of the ancestor
*/
function get_top_ancestor( $post ) {
if ( $post->post_parent ) {
$ancestors = get_post_ancestors( $post->ID );
$root = count( $ancestors ) - 1;
$parent = $ancestors[$root];
} else {
$parent = $post->ID;
}
return $parent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment