【问题标题】:PHP looping custom fields with bootstrapPHP使用引导程序循环自定义字段
【发布时间】:2017-11-01 23:14:02
【问题描述】:

所以我想重复这段代码。使用wordpress acf生成图片:

`<div class="row">
    <?php if( get_field('image_1') ): ?>
        <img class="this-image" src="<?php the_field('image_1'); ?>" />
    <?php endif; ?>
</div>`

我只是想知道如何循环这个我还需要增加数字(即 image_1、image_2、image_3)。

我在搞清楚PHP的逻辑时遇到了麻烦,如果已经有类似的帖子,将不胜感激,谢谢!

【问题讨论】:

  • 您可以使用For LoopWhile Loop 来完成此操作

标签: php html wordpress twitter-bootstrap advanced-custom-fields


【解决方案1】:

你可以试试这样的

`<div class="row">
    <?php 
    for (i=1; i<=3; i++) {
    if( get_field('image_'.i) ): ?>
        <img class="this-image" src="<?php the_field('image_'.i); ?>" />
    <?php endif; } ?>
</div>`

【讨论】:

    【解决方案2】:

    使用下面的代码 - 它使用 for 循环遍历从 image_1 到 image_X 的所有图像(其中 X 可以由您定义)。类似的代码可以通过添加一个数组来存储所有图像名称来修改,以防万一图像名称没有模式。

    <div class="row">
        <?php $numImages = 10; #Define how many images you have
         for ($i=1; $i<= $numImages; $i++){ #starting from image_1 ?>
        <?php if( get_field('image_' . $i)): ?>
              <img class="this-image" src="<?php the_field('image_' . $i); ?>" />
        <?php endif; ?>
        <?php } ?>
    </div>
    

    【讨论】:

    • 这完美!虽然我无法理解花括号在这种情况下是如何工作的?它只是帮助将 for 循环和 if 语句分开吗?
    • 只是for循环语法的简单开闭大括号,与foreach ($array as $item):endforeach;相同
    • 啊,我明白了。如果我想重复该行两次,同时在其中保持相同的 for 循环,怎么样?
    • 所以你把循环放到一个函数中,比如foo(),然后每次你需要使用循环时调用它。例如&lt;div class="row"&gt; &lt;!--row 1 --&gt; foo(); &lt;/div&gt;&lt;div class="row"&gt; &lt;!--row 2 --&gt; foo(); &lt;/div&gt;
    • 那还会按顺序递增吗?每次调用函数都不会重启?
    猜你喜欢
    • 1970-01-01
    • 2017-06-17
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多