Matthew Vaccaro

Coordinator of Internets
  • Index
  • Blog
  • Snippets
  • Get WP Utmost Parent

    I needed to highlight part of a large navigation menu, even when you are inside a sibling or child page of a parent page. So, we needed to find the top level ‘grandparent’ or ‘utmost parent’ of a page. In comes this little guy:

    Add this to your functions.php file:

    // Get grandparent page closest to the top
    function get_top_ancestor($id){
    $currentPage = get_post($id);
    if(!$currentPage->post_parent){
    return $currentPage->ID;
    } else {
    return get_top_ancestor($currentPage->post_parent);
    }
    }

    Put this in your page:

    $currPageID = get_the_ID();
    $currPageActive = get_top_ancestor($currPageID);

    Simple and useful!

    Go Back