计算 sub_field 中有多少行

Count how many rows are in sub_field

我正在使用高级自定义字段转发器加载一些 sub_fields,您可以在下面的代码中看到它:

<?php
    if( get_field('who_made_it') ): ?>
    <div id="role-wrapper">
        <?php while( has_sub_field('who_made_it') ): ?>
            <div class="role-item">
                <?php the_sub_field('job_role'); ?>
                <?php the_sub_field('description'); ?>
            </div>
        <?php endwhile; ?>
    </div>
<?php endif; ?>

我想计算一下有多少 .row-item,然后将该数字作为 class 打印在容器 #role-wrapper 上。

因此,作为 HTML 外观演示:

<div id="role-wrapper" class"roleitems-3">
    <div class="role-item">
        content in here
    </div>
    <div class="role-item">
        content in here
    </div>
    <div class="role-item">
        content in here
    </div>
</div>

我不熟悉 has_sub_fieldadvanced custom field repeater,但似乎一个简单的答案是添加一个计数器。

<?php 
$counter = 0;
while( has_sub_field('who_made_it') ):
    //do stuff
    $counter++;
endwhile;

//output the counter however you like
echo('<div class="counter">Total: ' . $counter . '</div>');
?>

the docs, get_field() returns an array() of sub fields in this case. As a result, you can do a simple count()指定:

<div id="role-wrapper" class"roleitems-<?php echo count( get_field('who_made_it') ); ?>">