Can is_page() be combined with a switch control structure?

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>

Related posts

Leave a Reply

2 comments

  1. 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
    }
    
  2. 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.