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


About the Author

Jacob Lett (Jake) is the founder of Bootstrap Creative, a B2B marketing consultancy specializing in manufacturers and industrial companies. A HubSpot-certified CMS developer, SEO, Answer Engine Optimization (AEO), and RevOps professional, he helps B2B companies improve their websites, search visibility, HubSpot systems, and Google Ads campaigns to generate more qualified leads and RFQs. With over a decade of hands-on experience, he acts as a direct partner for companies seeking measurable ROI from their marketing investment.



Related posts
Category: Code Snippets

Tags:

| Read My Editorial Policy

Want to Get Email Updates of New Articles?

Join My Email Newsletter