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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

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