繁体   English   中英

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

[英]Add image size depending on number of posts with counter in 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 来计算图像或通过 function 获取图像计数。

你遇到的问题是你不知道你的$count中有多少张图片,而你 output 在每个循环中。

但是$image-size中定义的内容不能用 css (如 nth-child 或 flexbox)实现您想要的吗?

在您的情况下,可能的解决方案是:

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

(代码未经测试)

暂无
暂无

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

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