posted on:August 7, 2009

WordPress Find Pages Top Level Parent ID


Here’s a short WordPress code that I wanted to share with you. I came across a little problem of displaying 2nd and 3d level of navigation in a sidebar no matter what page am I on. After googling for solution, I put together a pieces of a puzzle and came up with a short code snippet.

I created a new page in my theme that I’ll be using from now on for displaying side navigation from 2nd level downwards. I named it subnav.php and it’s included in my sidebar.php

<?php include("subnav.php"); ?>

Here’s the code from my subnav.php:

<?php

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

$children = wp_list_pages("title_li=&child_of=". $parent ."&echo=0");

if ($children) { ?>
<ul id="subnav">
<?php echo $children; ?>
</ul>
<?php } ?>

This code checks if the page we’re on (current page) has a parent. If so, that means that we are at least 2 levels deep in the navigation. In that case function get_post_ancestors is called. It returns an array of all the ancestors’ IDs up to the top level (root).
To get the ID of the top level ancestor we need to fetch the last item in that array.
On the other hand, if the page we’re on doesn’t have a parent it means we are currently on a top level page so we can use the current page ID.

Once we get the ID of the top level parent we can use it in wp_list_pages function to get its children.

Short’n’sweet, hope it helps somebody. 🙂 I’ll be using it that’s for sure!

Enjoyed the article?

Then don't miss our next one! Subscribe to our RSS feed or share it with your friends.

DeliciousStumbleUpon RedditSubscribe

Comments (6 Comments)

  1. Tyrone Avnit
    August 9, 2009

    Brilliant!!! I will be using it to! Thank you!
  2. Sarah Lewis
    August 18, 2009

    Thanks for this code snippet! It was exactly what I needed; I used it in conjunction with the body_class filter hook to do some fun per-section color changes. I really appreciate you taking the time to document your solution!
  3. Sudar
    August 19, 2009

    Thanks for sharing the code. Yes it is short and sweet but useful ;)
  4. Single Maria
    August 26, 2009

    Thanks for the post. Life seems much easier now with this code. I also have faced such a problem but didnt know what to do. Thanks God I came across your article)
  5. teknoloji
    August 31, 2009

    Thanks for sharing the code
  6. JonnyPage
    September 3, 2009

    any ideas on how to add a class to a specific level of page navigation?

Sorry, the comment form is closed at this time.