Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

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!

share|improve this answer
    
I'm going to go for this as this will also work on my CPTs. –  Brady Jun 12 '11 at 10:12
add comment

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.

share|improve this answer
add comment

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
}
share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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