Get the top level post for current post

August 22, 2013


function get_top_level($post){
 $parent = array_reverse(get_post_ancestors($post->ID));
 if(count($parent) > 0){
 $first_parent = get_page($parent[0]);
 }

$top_level_post = $post->post_parent > 0 ? $post->post_parent : $post->ID;
 if(count($parent) > 0 && $first_parent){
 $top_level_post = $first_parent->ID;
 }
 return $top_level_post;
}

Tags: ,

Leave a Comment