【问题标题】:ACF Image Field, get single values from array, instead of arrayACF 图像字段,从数组中获取单个值,而不是数组
【发布时间】:2016-09-07 15:46:21
【问题描述】:

我正在使用Advanced Custom Fields PRO Version 5.3.7。我正在尝试加载我的自定义帖子类型中的图片。

我已经为自定义帖子类型配置了 ACF 字段,它适用于文本相关字段。

但是,我正在尝试显示图像。我正在使用来自acf documentation 的改编示例。您可以在下面找到我的代码。

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

我的问题是,在我的网站上,我得到的是数组而不是单个值:

任何建议我的代码有什么问题?

感谢您的回复!

【问题讨论】:

  • $image = get_field('image'); 并检查 echo "&lt;pre/&gt;";print_r($image); 的输出结果,然后我们将为您提供帮助

标签: php wordpress advanced-custom-fields custom-fields


【解决方案1】:

不要使用the_field('box_image')['url'],因为the_field() 直接回显所有内容并回显数组输出array();而不是这个,试试这个:

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

【讨论】:

    【解决方案2】:

    设置 ACF 时,您可以选择“返回值”(数组、url、id)选项,如果您想获得不同的大小(缩略图),则将其更改为 id,如果您想获得原始图像 url,则更改为 URL。

    如果您使用 ID 选项将图像作为 html 标签获取,您可以使用 wp_get_attachment_image($id, $size); 我总是更喜欢只存储图像 ID。

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      相关资源
      最近更新 更多