Return Top Parent ID of Page/Post

February 19, 2014

When you work with pages (or posts), sometimes you want to find a top parent ID of a current page or post. This can be useful, for example, if you want to show sub navigation in sidebar.

function top_parent(){
	global $post;
	if ($post->post_parent) {
		$ancestors = get_post_ancestors($post->ID);
		$post_parent_id = array_pop($ancestors);
		return $post_parent_id;
	} else {
		return $post->ID;