Using a switch statement in WordPress

I’ve got a piece of text in a div that I want to change on each page of my website. At the moment I’m not sure what function I should be using to do this. Here’s what I have so far…

<?php
$page = is_page();
switch ($page){
case 'home':
$content = 'How much money....';
break;
case 'about':
$content = 'We design....';
break;
case 'services':
$content = 'At the....';
break;
case 'blog':
$content = 'Find out whats....';
break;
case 'portfolio':
$content = 'Unique, Beautiful....';
break;
case 'contact':
$content = 'Get in touch to....';
break;
case 'privacy-policy':
$content = 'How much money....';
break;
case 'terms-and-conditions':
$content = 'How much....';
break;      
}

echo '<div class="strapline strap">'.$content.'</div>';
?>

This code only seems to be picking up the first case for every page. Anyone know how I can get it to run through the switch completely?
Many thanks in advance!!

Related posts

Leave a Reply

3 comments

  1. If you wanted to use your switch statement, you could use:

    switch ($post->post_name){
        case 'home':
            $content = 'How much money....';
            break;
        case 'about':
            $content = 'We design....';
            break;
        case 'services':
            $content = 'At the....';
            break;
        case 'blog':
            $content = 'Find out whats....';
            break;
        case 'portfolio':
            $content = 'Unique, Beautiful....';
            break;
        case 'contact':
            $content = 'Get in touch to....';
            break;
        case 'privacy-policy':
            $content = 'How much money....';
            break;
        case 'terms-and-conditions':
            $content = 'How much....';
            break;      
    }
    
    echo '<div class="strapline strap">'.$content.'</div>';
    

    First. I would follow @rrikesh approach of using if/else and use is_page() correctly.

    But this code is really inefficient. If you can do an “is_page()” test, then you are on the page, and have access to it’s content. Personally, I would add a custom field to the pages to hold $content. Then on the pages, you can simply call the custom field

    $content = get_post_meta($post->ID, 'content', true);
    echo '<div class="strapline strap">'.$content.'</div>';
    

    You can use a free plugin like Advanced Custom Fields to quickly add a custom meta field to your pages and your content is easier to organize and edit later.

  2. I guess you should use if and else instead of a switch.

    is_page will just check if you are on a page and will return true or false. It will not return your page name.

    What you need to do:

    if ( is_page('Home') ){
      #do home stuff
    }
    elseif( is_page ('about') ){
      #do other stuff
    }
    elseif( is_page('services'){
      #do services stuff
    }
    

    Look at is_page for parameters you can pass.