If string is … then replace it with an image?

I have the following piece of code:

<?php echo get_custom_field('Services'); ?>

There are three possible string outputs for this: “food”, “drink”, “food & drink”.

Read More

I would like to replace these strings with small icons (e.g. a glass for “drink”).

Is there a simple way of doing this with PHP?

Thanks

Related posts

Leave a Reply

3 comments

  1. You could map the values via an array:

    $items = array(
        "Food" => "plate.png",
        "Drink" => "glass.png",
        "Food & Drink" => "tray.png"
    );
    

    Then perform your look-up when echoing the image:

    <img src="<?php echo $items[ get_custom_field('Services') ]; ?>" />
    
  2. You could use switch:

    <?php
            switch (get_custom_field('Services')) {
                    case "glass":
                            echo '<img src="glass.jpg" />';
                    break;
                    case "drink":
                            echo '<img src="food.jpg" />';
                    break;
                    case "food & drink":
                            echo '<img src="food-drink.jpg" />';
                    break;
                    default:
                            echo '<img src="noicon.jpg" />';
            }
    ?>
    
  3. Not a direct answer, but I would add a class to the (containing…) element and use css to remove the text and show a background image:

    php:

    <?php echo '<span class="' . $SERVICES_ID_OR_SOMETHING . '">' . get_custom_field('Services') . '</span>'; ?>
    

    css:

    .SERVICES_ID_OR_SOMETHING {
      background: url(/path/to/image) no-repeat left center;
      text-indent: -9999em;
    }