我想检查该字段是否有值(在本例中为图像),如果有,则它将显示图像。我不确定是否有更好的方法可以做到这一点。我觉得我用 if 语句做得太过分了。建议?
<img src="<?php the_field('image_1'); ?>" alt="">
<?php if (get_field('image_2')) : ?>
<img src="<?php the_field('image_2'); ?>" alt="">
<?php endif; ?>
<?php if (get_field('image_3')) : ?>
<img src="<?php the_field('image_3'); ?>" alt="">
<?php endif; ?>
<?php if (get_field('image_4')) : ?>
<img src="<?php the_field('image_4'); ?>" alt="">
<?php endif; ?>
<?php if (get_field('image_5')) : ?>
<img src="<?php the_field('image_5'); ?>" alt="">
<?php endif; ?>
<?php if (get_field('image_6')) : ?>
<img src="<?php the_field('image_6'); ?>" alt="">
<?php endif; ?>
当然有更好的方法:
<?php foreach (range(2,6) as $digit):
if (get_field("image_$digit")):
?>
<img src="<?php the_field("image_$digit") ?>" alt="" />
<?php
endif; endforeach; ?>
当你有一组彼此非常相似的代码行时,想想一种将它们变成循环的方法。情况就是如此,因为所有块仅在"image_N"var 中与 N 不同。
<?php
for($a=1;$a<=6;$a++){
$name = 'image_' . $a;
if(get_field($name){
echo "<img src='";
echo the_field($name);
echo "' alt='' />";
}
}
我不确定get_field或the_field功能是什么,所以我无法在那里帮助你。