Check Page Level Depth If Condition in WordPress


The code snippet below is handy when you are trying to check if the current page is a parent or a child in a WordPress theme. You can then use the conditional to output different code depending on the page depth it is

<?php
// gets page depth
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  ) {
    echo 'page level 0';

}  elseif ( $depth == 1 ) {
    echo 'page level 1';
} else {
    echo 'something else';
}?>

Source: Get the depth of the current page in WordPress



Written by: Jake Lett
Jake Lett is a results-driven B2B marketing consultant with 15+ years of experience helping businesses boost online visibility, generate qualified leads, and increase sales. Specializing in SEO, HubSpot, and PPC campaign management, Jake leverages proven strategies to deliver measurable growth. As a Certified Google Ads Specialist and HubSpot Developer, he is committed to driving impactful results for his clients.

Related posts

Tags:

Want to Get Email Updates of New Articles?

Join My Email Newsletter