我正在使用ACF,并建立了以下中继器:
<?php
$count = 0;
if( have_rows('image_builder') ):
while ( have_rows('image_builder') ) : the_row();
$count++;
?>
<?php
if ($count == 1) {
$image_size = 'there-is-1-image';
}
if ($count == 2) {
$image_size = 'there-are-2-images';
}
if ($count == 3) {
$image_size = 'there-are-3-images';
}
if ($count == 4) {
$image_size = 'there-are-4-images';
}
echo wp_get_attachment_image( get_sub_field('image'), $image_size );
?>
<?php
endwhile;
else:
echo '<p>Please add some images.</p>';
endif;
?>
中继器仅允许管理员添加多达4张图像。根据图像的数量,我希望应用一定的图像尺寸。
例如,如果添加了3张图像,我希望将$image-size
“有3张图像”应用于每张图像。
如您所见,我已经添加了计数器,但是我认为我使用的操作符不正确。
结果是:
<img src="/img-1.jpg" class="size-there-is-1-image">
<img src="/img-2.jpg" class="size-there-are-2-images">
<img src="/img-3.jpg" class="size-there-are-3-images">
正确的方法是什么?
在您的情况下,您需要一个foreach来计数图像或通过功能获得图像计数。
您的问题是,您不知道$count
中正在跟随多少图片,并且每个循环都输出。
但是$image-size
中定义的内容是否无法通过nth-child或flexbox之类的CSS实现您想要的?
您可能的解决方案是:
<?php
if( have_rows('image_builder') ):
$count = 0;
while ( have_rows('image_builder') ) : the_row();
$count++;
endwhile;
switch ($count) {
case 0:
$image_size = 'there-is-1-image';
break;
case 1:
$image_size = 'there-are-2-images';
break;
case 2:
$image_size = 'there-are-3-images';
break;
case 2:
$image_size = 'there-are-4-images';
break;
}
while ( have_rows('image_builder') ) : the_row();
echo wp_get_attachment_image( get_sub_field('image'), $image_size );
endwhile;
else:
echo '<p>Please add some images.</p>';
endif;
(未测试代码学家]