views:

24

answers:

2

I'm building a wordpress theme right now and I'm using conditionals in the sidebar to display different information for each page like so:

if (is_page('services')) {
 etc.....
} elseif (etc....

However, some of the subpages do not have their own specific conditional. How can I make it so that a conditional for a parent page applies to its subpages as well?

Thanks!

+1  A: 

You could do this a number of ways. There might be an easier way, but this is what I would do: On the page itself, check if it is a child page:

     if ( is_page() && $post->post_parent ) 
     {
          // This is a subpage
          return true;

     } 
     else 
     {
         // This is not a subpage
         return false;
     }

which will check if the page is a child, in which case you can fetch the conditional from the parent the same way you are currently, except specify the parent instead of the current page when checking.

gamerzfuse
This seems sort of a roundabout way to do this. (However, I don't claim to be any sort of expert in php. :D ) Shouldn't there be a way to specify in the conditional itself to include the subpages?
codedude
Or maybe there's a tag that looks like this: if(is_page_and_subpages('services')) {
codedude
I see what you want to do, but it's not that easy. It's not how PHP works as much as it is how Wordpress works. You could do this a number of other ways, but it's easier to do this than it is to pass a variable from parent to child. If I go directly to your child page, I never accessed your parent page, so the variable has to be set in a function or on the child page regardless. If that makes sense?
gamerzfuse
A: 

You can also put this snippet of code in your functions.php file and use it anywhere on your wp code.

    function is_subpage() {
    global $post;                                 // load details about this page
        if ( is_page() && $post->post_parent ) {      // test to see if the page has a parent
               $parentID = $post->post_parent;        // the ID of the parent is this
               return $parentID;                      // return the ID
        } else {                                      // there is no parent so...
               return false;                          // ...the answer to the question is false
        };
};

Source: http://codex.wordpress.org/Conditional_Tags

Beto Frega