0

I have the following code:

<?php 
$images = get_post_meta(get_the_ID(), 'pointb_portfolio_images', false);
$i = 0;
foreach ($images as $att) {
    $i++;
    $src = wp_get_attachment_image_src($att, 'full');
    $src = $src[0];
    echo "<img src='$src' class='t$i'/>";
}
?>

What I would like to do, is for every 9 images, place a DIV container around them. So it would be:

<div>9 images here</div>
<div>next 9 images here</div>
<div>next 9 images here</div>

I have an incremental class being applied to each image, and this would need to continue increasing upward.

I have been googling to try and find a solution for this, but I am struggling to find even the correct search query.

Would appreciate any assistance or tips so that I can accomplish what I need.

Thanks

4

1 回答 1

4

您可以使用%(modulus) 它找到余数。所以你要做的是你有一个if ($i % 9 == 0) ...然后关闭 9 个图像 div 并打开一个新的。该表达式将在每 9 次循环中验证为真。<div>在循环开始之前你也有一个开口,</div>在它完成之后有一个结束。

<?php 
$images = get_post_meta(get_the_ID(), 'pointb_portfolio_images', false);
$i = 0;

echo '<div>';

foreach ($images as $att) {
    // Moved this to the front of the loop so we don't have any empty div groups
    // in case 9 is a factor of the number
    if ($i > 0 && $i % 9 == 0) {
        echo '</div><div>';
    }

    $src = wp_get_attachment_image_src($att, 'full');
    $src = $src[0];

    // Added modulus to the class so now they will be t1, t2,... t8, t9, t1, t2...
    echo "<img src='$src' class='t" . ($i % 9 + 1) . "'/>";

    $i++;
}

echo '</div>';
?>

Modulus 返回的示例

 0 % 9 = 0
 1 % 9 = 1
 2 % 9 = 2
 3 % 9 = 3
 4 % 9 = 4
 5 % 9 = 5
 6 % 9 = 6
 7 % 9 = 7
 8 % 9 = 8
 9 % 9 = 0
10 % 9 = 1
11 % 9 = 2
于 2013-06-29T18:33:32.937 回答