Skip to content

Instantly share code, notes, and snippets.

@tarecord
Created June 6, 2017 18:22
Show Gist options
  • Save tarecord/b022e32b0df0d6c93bbbdc3c6927e563 to your computer and use it in GitHub Desktop.
Save tarecord/b022e32b0df0d6c93bbbdc3c6927e563 to your computer and use it in GitHub Desktop.
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