【问题标题】:If WordPress Repeater has 1 field, 2 fields etc else如果 WordPress Repeater 有 1 个字段,2 个字段等
【发布时间】:2014-12-31 18:22:28
【问题描述】:

我有一个中继器,我想根据它输出的字段数来改变它

我的基本转发器代码:

<?php // REAPEATER FIELD
if(get_field('whatever')): ?>
  <?php while(has_sub_field('whatever')): ?>

    <div class="whatever_block">
      <?php the_sub_field('anything'); ?>
    </div>

  <?php endwhile; ?>
<?php endif; ?>

我希望它看起来如何:

<?php // REAPEATER FIELD
if(get_field('whatever')): ?>
  <?php while(has_sub_field('whatever')): ?>

    //if only one
    <div class="col-sm-12">
      <?php the_sub_field('anything'); ?>
    </div>

    //if only two
    <div class="col-sm-6">
      <?php the_sub_field('anything'); ?>
    </div>

    //if etc

    //else
    <div class="whatever_block">
      <?php the_sub_field('anything'); ?>
    </div>

  <?php endwhile; ?>
<?php endif; ?>

如何使用 if 语句实现上述输出? if 语句甚至是正确的方法吗?

【问题讨论】:

  • 你有什么问题?
  • @Celeo ,当您发表评论时,我只是在更新我的问题。我正在尝试实现第二个版本(我希望它看起来如何)。所以我在想一个 if 语句,我会根据有多少项目来改变我输出的类。这更有意义吗?
  • 一次最多可以激活多少个字段?就像在 ACF 中一样,您是否设置了 Max 数?
  • @Joe,是的,我将最大数量设置为 4

标签: php wordpress if-statement advanced-custom-fields


【解决方案1】:

好的,这使用 count() 函数对字段进行计数,然后使用 switch case 为您的 div 设置一个类,如下所示:

<?php // REAPEATER FIELD
if(get_field('whatever')): ?>
    <?php switch(count(get_field('whatever'))) :    //checks total fields set
        case '1':
            $divClass = 'oneField';
            break;
        case '2':
            $divClass = 'twoField';
            break;
        case '3':
            $divClass = 'threeField';
            break;
        case '4':
            $divClass = 'fourField';
            break;
    endswitch; ?>
    <?php while(has_sub_field('whatever')): ?>

        <div class="<?php echo $divClass; ?>">
          <?php the_sub_field('anything'); ?>
        </div>

    <?php endwhile; ?>
<?php endif; ?>

只需将“oneField”、“twoField”等替换为您想要的类名,您就应该设置好了。

【讨论】:

  • 如果你尝试了我的回答,我发现了一些我刚刚在编辑中修复的小代码问题,所以这段代码现在应该可以工作了。
【解决方案2】:

您可以在转发器上执行count 来检查它有多少子字段。这是使用 ACF v4.xx have_rows syntax 的解决方案(但也应与 get_field 一起使用):

if( have_rows( 'parent_whatever' ) ) {
    $posts_no = get_field( 'parent_whatever' );
    while( have_rows( 'parent_whatever' ) {
        the_row();
        $class = "col-sm-" . 12/$posts_no;

        echo '<div class="' . $class . '">';
        the_sub_field( 'whatever' );
        echo '</div>';
    endwhile;
endif;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2012-01-13
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多