首页 > 解决方案 > 根据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">

这样做的正确方法是什么?

标签: phpwordpressadvanced-custom-fields

解决方案


在您的情况下,您需要一个 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;

(代码未经测试)


推荐阅读