tarecord
6/6/2017 - 6:22 PM

Get the top most parent of a WordPress post

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;
}