0

WordpressのAdvancedCustomFieldsプラグインを使用して、自分のサイトにギャラリーを実装しています。ギャラリーフィールドからランダムに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 に答える