Reputation: 831
I have a repeater that I would like to alter based on how many fields it out puts
the code I have for the basic repater:
<?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; ?>
How I want it to look:
<?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; ?>
How I can achieve the above above output with if statements? are if statements even the correct way to go?
Upvotes: 0
Views: 509
Reputation: 3220
You can do a count
on the repeater to check how many sub fields it has. Here is a solution using the ACF v4.xx have_rows
syntax (should nevertheless work with get_field
as well):
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;
Upvotes: 0
Reputation: 1822
Ok, this uses the count() function to count the fields, then use a switch case to set a class for your div, like this:
<?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; ?>
Just replace 'oneField', 'twoField', ect with your desired class names, and you should be set.
Upvotes: 2