probablybest
probablybest

Reputation: 1445

Count how many rows are in sub_field

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>

Upvotes: 0

Views: 4060

Answers (2)

rnevius
rnevius

Reputation: 27102

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

Upvotes: 3

KnightHawk0811
KnightHawk0811

Reputation: 931

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

Upvotes: 2

Related Questions