JakeParis
JakeParis

Reputation: 11210

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:

  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?

Upvotes: 3

Views: 3097

Answers (1)

JakeParis
JakeParis

Reputation: 11210

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

Upvotes: 12

Related Questions