简体   繁体   中英

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:

在此处输入图片说明

Any suggestions what is wrong with my code?

I appreciate your replies!

Whn you setting a ACF, you can select options "Return value" (array, url, id) change this as id if you want get different sizes (thumbnails), and URL if you want get original image url.

if you use ID option to get image as html tag you can use wp_get_attachment_image($id, $size); i always prefer to store only image ID.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM