A function like is_page() but returns true if on any sub page of given page

In my header I use this code:

if(is_page("stores")) {
    // Do something
}

I run some code if on the page stores but what I want to do is run that code if the page is stores or any page that is a sub page of stores. Not only that, but is recursive so if we are on a sub sub sub page of stores the code still runs.

Related posts

Leave a Reply

3 comments

  1. When using pretty permalinks, I simply check against the request;

    if ( preg_match( '#^stores(/.+)?$#', $wp->request ) ) {
        // away we go!
    } 
    

    No extra DB queries, little computation, and works right down the tree!

  2. Handy little function

     function is_child_of($parent) {
        global $post;
        if ( $post->post_parent == $parent){
            return true
        }else{
            $curent_parent = $post->post_parent;
            $dec = false;
            while ($curent_parent > 0){
                $p = get_post($curent_parent);
                $curent_parent = $p->post_parent;
                if ($curent_parent > 0){
                    if ($curent_parent == $parent){
                        return true;
                    }
                }
            }
        return false;
    }
    

    Usage:
    check if current is a child of a page with the ID of 22

    if (is_child_of(22)){
      //its a child of 22
    }