0

我正在使用 Wordpress 中的高级自定义字段插件在我的网站中实现图库。我想显示来自画廊字段的 5 张随机图像。

我有以下代码显示画廊字段中的所有图像:

    <?php $images = get_field('gallery');
      if( $images ): ?>
        <?php foreach( $images as $image ): ?>
          <img scr="<?php echo $image['url']; ?>">
        <?php endforeach; ?> 
    <?php endif;  ?>

$images 的 Print_r 产生以下输出:

Array ( [0] => Array ( [id] => 46 [alt] => [title] => 500x10002 [caption] =>  [description] =>   [url] => 500x1000.jpg [sizes] => Array ( [thumbnail] => 500x1000-100x100.jpg [medium] => 500x1000-150x300.jpg [large] => 500x1000.jpg [post-feature-image] => 500x1000.jpg ) ) [1] => Array ( [id] => 45 [alt] => [title] => 500x500 [caption] => [description] =>   [url] => 500x500.jpg [sizes] => Array ( [thumbnail] => 500x500-100x100.jpg [medium] => 500x500-300x300.jpg [large] => 500x500.jpg [post-feature-image] => 500x500.jpg ) ) [2] => Array ( [id] => 44 [alt] => [title] => 2000x500 [caption] => [description] =>   [url] => 2000x500.jpg [sizes] => Array ( [thumbnail] => 2000x500-100x100.jpg [medium] => 2000x500-300x75.jpg [large] => 2000x500-1024x256.jpg [post-feature-image] => 2000x500-610x152.jpg ) ) [3] => Array ( [id] => 43 [alt] => [title] => 1000x500 [caption] => [description] =>   [url] => 1000x500.jpg [sizes] => Array ( [thumbnail] => 1000x500-100x100.jpg [medium] => 1000x500-300x150.jpg [large] => 1000x500.jpg [post-feature-image] => 1000x500-610x305.jpg ) ) [4] => Array ( [id] => 42 [alt] => [title] => 500x2000 [caption] => onderschifttttt [description] =>   [url] => 500x2000.jpg [sizes] => Array ( [thumbnail] => 500x2000-100x100.jpg [medium] => 500x2000-75x300.jpg [large] => 500x2000-256x1024.jpg [post-feature-image] => 500x2000.jpg ) ) ) 

非常感谢任何帮助。

4

1 回答 1

0

您的逻辑可能如下所示:

$max_images_to_show = 5;
$images_available = count($images);
$images_to_show = array();

if ($images_available <= $max_images_to_show) {
    $images_to_show = $images;
} else {
    while(count($images_to_show) < $max_images_to_show) {
        $random_index = rand(0, count($images) - 1);
        $images_to_show[] = array_slice($images, $random_index, 1);
    }
}

// show images from $images_to_show
于 2012-11-29T22:30:18.547 回答