If string is … then replace it with an image?

2019-07-21 18:36发布

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

标签: php wordpress
3条回答
成全新的幸福
2楼-- · 2019-07-21 18:52

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') ]; ?>" />
查看更多
姐就是有狂的资本
3楼-- · 2019-07-21 18:56

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" />';
        }
?>
查看更多
Melony?
4楼-- · 2019-07-21 18:57

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;
}
查看更多
登录 后发表回答