Get the depth of the current page in WordPress

If you want to get the level of the current page in WordPress you can use this 

// gets the depth of the current page
global $wp_query;
$object = $wp_query->get_queried_object();
$parent_id  = $object->post_parent;
$depth = 0;
while ($parent_id > 0) {
       $page = get_page($parent_id);
       $parent_id = $page->post_parent;
       $depth++;
}

echo $depth;

 This function will echo the depth of the current page. If the depth returned is zero then you’re on a parent page.

One thought on “Get the depth of the current page in WordPress

  1. Or you could use something like this:

    $ancestors=get_post_ancestors($post->ID);
    $root=count($ancestors)-1;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s