Question

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.

Was it helpful?

Solution

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!

OTHER TIPS

Testing for sub-Pages section of Conditional Tags article in Codex has fitting code example that uses get_post_ancestors() to retrieve parent tree and loops through it with check.

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top