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. User Avatar
    samavia
    Permalink to comment#

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

  2. User Avatar
    Scott
    Permalink to comment#

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

  3. User Avatar
    Jonathan
    Permalink to comment#

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

  4. User Avatar
    porluffy
    Permalink to comment#

    Use this one $post->post_parent

  5. User Avatar
    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;
    }
    
  6. User Avatar
    Bogdan Günther
    Permalink to comment#

    Thank you, very helpful!

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag