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"'; }
  • 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

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
  • Wonderful! Exactly what I needed. Thanks for you help. – seron Sep 11 '12 at 17:34

Ok, now we have something to work with.

    case "project" :
        echo 'class="project"';
    case "home" :
        echo 'class="home"';
    case "contact" :
        echo 'class="contact"';

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.

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.