Forums

[resolved] Get page hierarchy (4 posts)

  1. sarthemaker
    Member
    Posted 2 years ago #

    I have a loop that goes through all of the pages in my blog, but is there a way to retrieve the hierarchy of the current page? e.g. top-level, child, grandchild
    Thanks

  2. MichaelH
    Volunteer
    Posted 2 years ago #

    See Function_Reference/get_pages and the child_of argument

  3. sarthemaker
    Member
    Posted 2 years ago #

    I am using a child_of loop within my page loop to add the child pages to a drop down list. But within the child_of loop, I need to find what level it is at, or how many parents it has. This is my code:

    <?php foreach(get_pages('sort_column=menu_order&parent=0') as $page) { ?>
    <li class="page_item page-item-<?php echo $page -> ID; ?><?php if($_GET['page_id'] == $page -> ID) { echo ' current_page_item'; } ?>">
    <a href="<?php echo bloginfo('url') . "/?page_id=" . $page -> ID; ?>">
    <?php echo $page -> post_title; ?>
    </a>
    <?php if(get_pages('child_of='.$page->ID)) { ?>
    <ul class="<?php echo $page -> ID; ?> child">
    <?php foreach(get_pages('child_of='.$page->ID) as $child) { ?>
    <li class="page_item page-item-<?php echo $child -> ID; ?><?php if($_GET['page_id'] == $child -> ID) { echo ' current_page_item'; } ?>">
    <a href="<?php echo bloginfo('url') . "/?page_id=" . $child -> ID; ?>">
    <?php echo $child -> post_title; ?>
    </a>
    </li>
    <?php } ?>
    </ul>
    <?php } ?>
    </li>
    <?php } ?>

    within the second foreach loop, I need to find what hierarchy level the $child is at.

  4. sarthemaker
    Member
    Posted 2 years ago #

    I figured it out, I used an array $hierarchy and set:

    $hierarchy[$page -> ID] = 0;
    $hierarchy[$child -> ID] = $hierarchy[$child -> post_parent] + 1;

    this stored the hierarchy of each page for later use.

Topic Closed

This topic has been closed to new replies.

About this Topic