How to find out what level of hierarchy the current page is?

On my WordPress site, I want to display a list of pages in the current site section. It needs to get different levels of pages depending on what level in the hierarchy the current page resides.

For instance:

Read More
  1. Top level page: the list shouldn’t display at all.
  2. Second level page: the list should display only child pages of the current page.
  3. Third level page: the list should display sibling pages and child pages.

What is the simplist way to find out what level of the heirarchy the current page is on?

Related posts

Leave a Reply

1 comment

  1. The simplest way I’ve found is:

    $level = count(get_post_ancestors( $post->ID )) + 1;
    

    This simply gives you a number indicating the depth of the current page. 1 is top level, 2 is second level, etc. Then you can switch code based on the number as such:

    switch($level) {
        case 1:
            // top level page code;
        break;
        case 2:
            // second level page code;
        break;
        case 3:
            // third level page code;
        break;
    
        // etc.
    }