Page Depth Condition

Comes in handy working with breadcrumbs, and sub-pages showing parent’s title.

<?php
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;
?>
 
<?php if ( $depth == 0  ) {
    // top level
}  elseif ( $depth == 1 ) {
    // do something for first child
} else {
    // do something for all other instances
} ?>

Source.

Leave a Reply

Posted in php
katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.