簡體   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