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.

I'm using an if/else control structure to add class attributes to tags. Could I use a switch control structure instead and if so, how? If not, is there a better way to do this than what I'm doing?

<div <?php if (is_page( 'project' )) { echo 'class="project"'; }
        elseif (is_page('home')) {echo 'class="home"'; }
        elseif (is_page('contact')) {echo 'class="contact"'; }
    ?>>
</div>
share|improve this question
1  
How should we give you an answer without seeing the code you're already using? It's hard to imagine what you're after without code. Please add it. Thanks. –  kaiser Sep 11 '12 at 12:05
    
This is an abstract concept question. And a simple at that. Do you consider it unwarranted? If so, why? –  seron Sep 11 '12 at 16:34

2 Answers 2

up vote 1 down vote accepted

While Ben's answer is basically correct, is_page also checks to make sure that the query is indeed a Page and not something else with the same post_name.

So to be 100% accurate, you could do something like this:

if ( is_page() ) { // only do this for actual pages
  $page_obj = get_queried_object();
  switch ( $page_obj->post_name ) {
    // same switch as Ben's answer
  }
} else { 
  // not a page
}
share|improve this answer
    
Wonderful! Exactly what I needed. Thanks for you help. –  seron Sep 11 '12 at 17:34

Ok, now we have something to work with.

switch($post->post_name)
{
    case "project" :
        echo 'class="project"';
        break;
    case "home" :
        echo 'class="home"';
        break;
    case "contact" :
        echo 'class="contact"';
        break;
}

A switch is a way for saying "pick one of these choices based on this variables value" but an if/else statement is just a series of boolean checks. So, in your instance, a switch is the clear winner.

share|improve this answer

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.