WordPress – Get depth of pages and subpages

by
on September 21, 2011
(1 minute read)

This is how you can get how deep a page is compared to the root/home page in WordPress, works for both the current page or any page by providing its ID. Copy this script and paste it in your functions.php file:

function get_depth($postid) {
  $depth = ($postid==get_option('page_on_front')) ? -1 : 0;
  while ($postid > 0) {
    $postid = get_post_ancestors($postid);
    $postid = $postid[0];
    $depth++;
  }
  return $depth;
}

I’ve got invites for a free bank transfer!

Now paste this anywhere in a loop:

echo get_depth($post->ID);

Other solutions I’ve found on the Internet where 50 lines long or even 100 and they where full of loops and slow, that’s why I decided to code this one.

The home page will return 0, direct childs will return 1, childs of childs will return 2, etc.

One line Alternative

You can also use this one:

echo count($post->ancestors);

Simple Cloud Hosting Built for Developers

Although it will not differentiate between the home page and level 1 pages (will output 0).

That’s it, easy as pie! If you maintain WordPress sites or are a theme developer see this post on advanced tips to improve performance and gain space in WordPress.

Looking for cool gift ideas? TrendLiker.com lists hundreds of nice items and lets you know when they go on sale on Amazon.

Did you enjoy this article?

Grab me a coffee ☕

2 comments

  • marc says:

    awesome xavi, de pm!

  • aaron says:

    Hi xavi,

    This is working fine for me when debug mode is set to false. However, when set to true I’m getting an error stating……

    Undefined offset: 0 on line $postid = $postid[0];

    Any idea why this might be happening?

    Thanks
    A

Follow me for cool new products and interesting findings on graphic design, web development, marketing, startups, life and humor.


/*Twitter*/ !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); /*Facebook (function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) {return;}js = d.createElement(s); js.id = id;js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=28624667607";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));*/ /*Google+*/ window.___gcfg = {lang: 'en-GB'};(function() {var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;po.src = 'https://apis.google.com/js/plusone.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);})();
Airbnb 25€ discount