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; }
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);
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.
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