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

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".