Wordpress =显示来自图库字段的随机选择图像的数量

时间:2012-11-29 22:17:29

标签: php wordpress

我正在使用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 ) ) ) 

非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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