Count how many rows are in sub_field

≯℡__Kan透↙ 提交于 2019-12-10 12:17:49

问题


I am using advanced custom field repeater to load some sub_fields which you can see in the below code:

<?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; ?>

I would like to count how many .row-item's there are and then print that number as a class on the container #role-wrapper .

So as a HTML demo of how it would look:

<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>

回答1:


As specified by 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') ); ?>">



回答2:


I am unfamiliar with has_sub_field and the advanced custom field repeater, but it seems a simple answer would be to add a counter.

<?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>');
?>


来源:https://stackoverflow.com/questions/32380146/count-how-many-rows-are-in-sub-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!