How to get top parent page ID in wordpress

The solution to get the top parent page id is here, it is quite easy without using any recursion function.

function get_top_parent_page_id() {

global $post;

// Check if page is a child page (any level)
if ($post->ancestors) {

//  Grab the ID of top-level page from the tree
return end($post->ancestors);

} else {

// Page is the top level, so use  it’s own id
//return $post->ID;
return 1;

}

}

Drop the above function in your theme functions.php file and call like below example.

echo get_top_parent_page_id();

Share This Post

One Response to "How to get top parent page ID in wordpress"

Post Comment