高级自定义字段数字图像随机

Advanced Custom Fields number image random

如何在acf中随机显示x张图片

我有在acf中随机添加代号数字图片不显示图片

<?php 
$images = get_field('khach_hang', 'option');
$rand = array_rand($images, 1);
if( $images ): ?>
<?php 
$i = 0;
foreach( $images as $image ): 
if ($i <= 19 ) { ?>
        <img class="khac_hang_item" src="<?php echo $image[$rand]['url']; ?>" alt="<?php echo $image[$rand]['alt']; ?>" />
<?php $i++; }  endforeach; ?>
<?php endif; ?>

我有 20 张 url 图片:<img class="khac_hang_item" src="" alt="" />

非常有帮助,谢谢

$rand 将是来自 $images..

的键数组

我猜你应该将代码重写成这样:

<?php 
$images = get_field('khach_hang', 'option');
if( $images ):
$rand_keys = array_rand($images, 10);
foreach( $rand_keys as $key ): ?>
    <img class="khac_hang_item" src="<?php echo $images[$key]['url']; ?>" alt="<?php echo $images[$key]['alt']; ?>" />
<?php  endforeach; ?>
<?php endif; ?>

你应该循环 $rand_keys 而不是 $images...