1

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.

4

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!

3
  • I'm going to go for this as this will also work on my CPTs.
    – Scott
    Jun 12 '11 at 10:12
  • 1
    $wp needs to be defined as a global for this to work outside of the loop. thusly global $wp; if you want to create a function in functions.php
    – dgrebb
    Jun 30 '16 at 13:38
  • 1
    @dgrebb To be clear $wp needs to be global'd inside functions and files outside of "normal" WP, but any template loaded in via the template system will already have the $wp variable available - in or outside the loop. Oct 26 '16 at 8:59
4

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.

4

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
}
2
  • I don't think this is a great answer, because I don't think it answers the question very well. It's not recursive, and it's not a step-in equivalent of is_page() as you can only pass the page ID. is_page() supports ID, slug and name. I hope this doesn't sound obnoxious, just just disagree :s
    – Joe Hoyle
    Jun 11 '11 at 16:11
  • @Joe my bad, i didn't read the whole question, anyway i updated the answer with an altered function which works but on page id only no names or slugs, which shouldn't be too hard to add, simply query the passed $parent if its not an integer using pagename parameter.
    – Bainternet
    Jun 11 '11 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.