Search code examples
phpwordpressadvanced-custom-fields

How to loop through image fields with foreach in ACF only if there's a value?


I am using ACF for the first time. I'm trying to loop through all fields of a field group, where each field has a field type of image, and then only display the field if it has a value. I've altered the function ACF offers for hiding empty fields slightly, but I'm having trouble finding the right code to render the image.

I have the following:

            <?php 
   
        $fields = acf_get_fields('group_6301b69438031');
        $image = array();
        if($fields) : ?>            
            <div class="col-md-3">      
                <?php foreach( $fields as $field ): 
                   $image[] = $field['url']; ?>
                    <?php if( $field['value'] ): ?>
                        <img src="<?php echo $image; ?>" class="services-img"/>                         
                        
                    <?php endif ?>
                <?php endforeach; ?>
                <?php  else : { 
                       echo '<h3> No services have been selected!</h3>';
                        }  ?>
            </div>
        
          <?php endif ?>

I've played around with setting the image type return as an object and as just a URL and updated the code to reflect either of those options and still no dice.


Solution

  • Here's how it'll work:

    $group = acf_get_fields('group_6301b69438031');
    foreach($group as $image){
        $url = get_field($image['key']);
        if ($url) {
            echo '<img src="'.$url.'" class="services-img"/>';
        }
    }
    

    Make sure that the output of the image fields is set to "Image URL"

    I've tested this on my local and it's working fine.