如果WordPress Repeater有1个字段,2个字段等

时间:2014-11-04 18:24:58

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

我有一个转发器,我想根据它输出的字段来改变

我对基本报告者的代码:

<?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 if statement甚至是正确的方法吗?

2 个答案:

答案 0 :(得分:2)

好的,这使用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'替换为您想要的类名,就可以设置。

答案 1 :(得分:0)

您可以在转发器上执行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;