0

I have an Advanced Custom Fields Checkbox that I'd that I need to do some checks on. If a checkbox is ticked in the back end, it outputs an appropriate image on the front end. I've got some code that "works" but I think there's gotta be a much more efficient way to do it.

Here's the code

$gluten = 'gluten.png';
$vegan = 'vegan.png';
$vegetarian = 'vegetarian.png';
$dish = get_field('diet_friendly');

if( in_array( 'gluten', get_field('diet_friendly') ) )
 {
    echo '<img src="';
    echo get_template_directory_uri().'/images/'.$gluten.'" alt="Gluten Free" />';
 }
if( in_array( 'vegan', get_field('diet_friendly') ) )
 {
    echo '<img src="';
    echo get_template_directory_uri().'/images/'.$vegan.'" alt="Vegan Friendly" />';
 }

Here's the array of the checkbox field

array(2) { [0]=> string(6) "gluten" [1]=> string(5) "vegan" }
3

You're assigning a value to $dish, but then not using it...

Try the following. It takes advantage of the fact that your image for "gluten" is named gluten.png, etc. You'll be able to add more tags by just adding to the $images array.

$images = array(
    "gluten"     => "Gluten Free",
    "vegan"      => "Vegan Friendly",
    "vegetarian" => "Vegetarian"
);
$dish_tags = (array) get_field('diet_friendly');

foreach ($images as $image_name => $alt) {
    if (in_array($image_name, $dish_tags)) {
        echo '<img src="' . get_template_directory_uri() . '/images/' .
            $image_name . '.png" alt="' . $alt . '" />';
    }
}
  • thank you! That works a treat alright! The problem is that if a checkbox is not selected then the following error pops up: Warning: in_array() expects parameter 2 to be array Any thoughts there? – yannibmbr Jul 18 '14 at 20:52
  • 1
    you could try casting $dish_tags as an array: $dish_tags = (array) get_field('diet_friendly'); or wrapping your foreach in an if statement: if ( is_array( $dish_tags ) ) { /* foreach here */ } – karpstrucking Jul 18 '14 at 22:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.