php - 根据WordPress中带有计数器的帖子数量添加图像大小
问题描述
我正在使用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
“there-are-3-images”应用于每张图像。
如您所见,我添加了计数器,但我认为我使用的运算符不正确。
结果是:
<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;
(代码未经测试)
推荐阅读
- sql - 寻找类似 Lag 函数但更复杂的东西 (SQL)
- apollo-federation - 当实体是另一个实体的本机时,为什么我会在一个服务中看到 _entities 请求?
- ios - 只能通过wifi连接到CloudKit的公共容器,不能通过蜂窝连接
- reactjs - 嵌套的 React 路由不显示内容
- android - firebase 实时数据库事务和多位置写入在一起?
- javascript - ajax jQuery在浏览器页面刷新时自动重新加载数据
- android - 使用 Gson 将 VideoView 对象解析为 json
- c++ - C++ CodeBlocks 升级到 C++17 不能使用 std::filesystem
- javascript - 世博会 Location.reverseGeocodeAsync 问题
- amazon-web-services - AWS Connect API CORS 问题