Search code examples
phpwordpressadvanced-custom-fieldscustom-fields

ACF Image Field, get single values from array, instead of array


I am using Advanced Custom Fields PRO Version 5.3.7. I am trying to load a picture that is within my custom post type.

I have configured the ACF field for the custom post type and it works well for text related fields.

However, I am trying to display an image. I am using an adapted example from the acf documentation. Below you can find my code.

<div class="image">
    <a href="<?php the_field('link'); ?>" rel="nofollow" class="am" target="_blank" > <img class="b-lazy wp-post-image b-loaded" alt="<?php echo the_field('box_image')['alt']; ?>" src="<?php echo the_field('box_image')['url']; ?>" width="230"> </a>
</div>

My problem ist that on my site, I get the Array back instead of the single value:

enter image description here

Any suggestions what is wrong with my code?

I appreciate your replies!


Solution

  • Dont use the_field('box_image')['url'] because the_field() echoes directly everything and echoing an array outputs array(); Instead of this, try this:

    <?php $img = get_field('box_image'); ?>
    <?php if( $img ): ?>
      <a href="<?php the_field('link'); ?>" rel="nofollow" class="am" target="_blank" >
        <img class="b-lazy wp-post-image b-loaded" alt="<?php esc_attr_e( $img['alt'] ); ?>" src="<?php echo esc_url( $img['url'] ); ?>" width="230">
      </a>
    <?php endif; ?>