search ]

Check if Current Page Is a Parent or Child Page

WordPress has a built-in function to check if you are on a specific page:

if ( is_page(5) ) {
        // do some stuff
    }

Or whether the page is a child of a specific page:

if ( $post->post_parent == '5' ) {
        // do some stuff
    }

But there is no built-in WordPress function that checks both conditions together, and this is very useful. For example – if we want to load a JS file for a videos page and all pages under it…

The following function (add to functions.php) creates a new logical function for this check:

function is_tree($the_page_id) {   
    global $post;         

    if(is_page()&&($post->post_parent==$the_page_id||is_page($the_page_id))) 
       return true;   
    else 
       return false;   
    };

Usage

if (is_tree(5)) {
        // do some stuff
    }

For more on WordPress page templates, see WordPress Template Hierarchy.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo