简体   繁体   English

根据 WordPress 中计数器的帖子数量添加图像大小

[英]Add image size depending on number of posts with counter in WordPress

I'm using ACF and have built the following repeater:我正在使用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;
?>

The repeater simply allows admin to add up to 4 images.中继器只允许管理员添加最多 4 个图像。 Depending on the number of images, I'd like a certain image size to be applied.根据图像的数量,我希望应用特定的图像大小。

For example, if 3 images have been added, I'd like the $image-size "there-are-3-images" to be applied to each image.例如,如果添加了 3 张图片,我希望将$image-size "there-are-3-images" 应用于每张图片。

As you can see, I've added my counter, but I don't think I'm using the correct operator.如您所见,我添加了计数器,但我认为我使用的运算符不正确。

The result is:结果是:

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

What's the correct way to do this?这样做的正确方法是什么?

In your case you need one foreach to count the images or get the image count via a function.在您的情况下,您需要一个 foreach 来计算图像或通过 function 获取图像计数。

The problem you've is that you can't know how many pictures are following in your $count and you output in every loop.你遇到的问题是你不知道你的$count中有多少张图片,而你 output 在每个循环中。

But what is defined in $image-size can`t you achieve what you want with css like nth-child or flexbox?但是$image-size中定义的内容不能用 css (如 nth-child 或 flexbox)实现您想要的吗?

In your case a possible soulution is:在您的情况下,可能的解决方案是:

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

(The code ist not tested) (代码未经测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM