user1444027
user1444027

Reputation: 5241

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".

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

Upvotes: 2

Views: 233

Answers (3)

Sampson
Sampson

Reputation: 268424

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') ]; ?>" />

Upvotes: 4

jeroen
jeroen

Reputation: 91762

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;
}

Upvotes: 1

Emmanuel Tabard
Emmanuel Tabard

Reputation: 696

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

Upvotes: 1

Related Questions