使用高级自定义字段(ACF),我通常使用以下代码来显示具有特定缩略图大小的特定字段(使用图像ID):
$image = get_field('field_name_here');
$size = 'thumbnail_size_here';
if( $image ) {
echo wp_get_attachment_image( $image, $size );
}
然而,当我试图在中继器字段中使用此代码时,它只会吐出数字。
我已尝试将上述代码更新为:
$image = the_sub_field('field_name_here');
$size = 'thumbnail_size_here';
if( $image ) {
echo wp_get_attachment_image( $image, $size );
}
然而,这不起作用,它只是吐出数字。完整的代码如下:
<?php if(get_field('example_repeater_field')): ?>
<ul>
<?php while(has_sub_field('example_repeater_field')): ?>
<li>
<?php
$image = the_sub_field('field_name_here');
$size = 'thumbnail_size_here';
if( $image ) {
echo wp_get_attachment_image( $image, $size );
} ?>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
我已经阅读了ACF网站上的信息,但看不到任何与自定义缩略图大小有关的信息。
以前有人遇到过这种情况并找到了解决方案吗?
我不太喜欢while
循环和多个请求,所以我通常更喜欢只用一个请求获取数据,然后用foreach
循环通过它,如下所示:
<?php $fields = get_field('repeater_field'); ?>
<?php foreach ($fields as $field): ?>
<?= $field['field_name']; ?>
<?php endforeach; ?>
此外,您可以尝试将图像字段设置为返回图像对象(而不是id),并像这样显示图像:(请参阅"自定义显示(对象)"部分)
<?php $image = get_field('image'); ?>
<?php echo $image['sizes']['thumbnailSize']; ?>
在你的情况下,它会给我们这样的东西(一旦你设置了你的acf字段来返回一个对象):
<?php $fields = get_field('repeater_field'); ?>
<?php if( !empty($fields) ): ?>
<ul>
<?php foreach ($fields as $field): ?>
<li><?= $field['field_name']['sizes']['thumbnail_size']; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
我在中继器场环路中得到了这个
<?php if(have_rows('column')):
while(have_rows('column')) : the_row(); ?>
<?php $image = get_sub_field('image');
if( !empty($image) ):
$url = $image['url'];
$caption = $image['caption'];
// thumbnail size (column) declared in functions.php
$size = 'column';
$thumb = $image['sizes'][ $size ]; ?>
<?php endif; ?>
<img src="<?php echo $thumb; ?>">
但只有当您的返回值在ACF 中设置为"image array"时,这才有效