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();

Bansal Sumit

To seek challenging roles and to achieve excellence in the field of Open Source Web Technology with a profound spirit of commitment and dedication.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.