Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Find ID of Top-Most Parent Page

This will find what the ID is of the top-most parent Page, in a nested child page. For example, this page you are literally looking at is nested under

<?php

if ($post->post_parent)	{
	$ancestors=get_post_ancestors($post->ID);
	$root=count($ancestors)-1;
	$parent = $ancestors[$root];
} else {
	$parent = $post->ID;
}

?>

$parent will be the correct ID. For example, for use with wp_list_pages.

Source: CSSGlobe

Comments

  1. samavia
    Permalink to comment#

    Really nice .. it works… it save me from frustration..thanks :)

  2. Scott
    Permalink to comment#

    This is just what I needed for what I was working on today. Thanks!

  3. Perfect! Thanks .. i need it today for my work, it safe my time :)

  4. Use this one $post->post_parent

  5. Matt
    Permalink to comment#

    Perfect! This was a great time-saver. If you’d like to place this in your functions.php file for repeated use, you could wrap it in a function like this:

    function get_top_parent_id($post){
      if ($post->post_parent)   {
        $ancestors=get_post_ancestors($post->ID);
        $root=count($ancestors)-1;
        $parent = $ancestors[$root];
      } else {
        $parent = $post->ID;
      }
      return $parent;
    }
    

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```