Get page depth (3 posts)

  1. Joe Hoyle
    Human Made
    Posted 9 years ago #


    Is it possible to use a template tag to get the current page depth as I want to style sub pages slightly differently to the parent pages. If I could get the current page depth I could create a simple If statement to run whatever code when the page has a depth of > 1.


  2. kath
    Posted 9 years ago #

    I need to do this too. Anyone know how?

  3. Aleister
    Posted 9 years ago #

    Here is some code you can use:

    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;
    echo $depth;

    If you add that in the loop in your page.php file, it will display the depth of the page. You could use the $depth value in a conditional statement instead of course.

    Main pages will show a depth of 0, sub pages 1, 2, etc..

Topic Closed

This topic has been closed to new replies.

About this Topic