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```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

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