Reputation: 269
I have an ACF repeater field which pulls in images to an image slider.
if the user uploads just the one image the slider breaks.
So i need to count the repeater fields and then show two outputs.. One as a slider and one as a static image (if only one row)
here is my code so far:
<div class="full-img-slider">
<?php while( have_rows('top_images') ): the_row();
$image = get_sub_field('image');
?>
<img src="<?php echo $image; ?>">
<?php endwhile; ?>
</div>
<!-- Close full image slider -->
<?php endif; ?>
is there a way of saying if over 2 rows echo this?
I am not very PHP savvy.
Upvotes: 1
Views: 2696
Reputation: 178
// get the count on the repeater field
// mabye use get_sub_field() instead of get_field() if it's nested
$count = count( get_sub_field( 'the_field' ) );
// begin $count conditions
if ( $count > 1 ) {
the_field( 'great_than_1' );
} else {
the_field( 'less_than_1' );
}
may be it will help..
https://support.advancedcustomfields.com/forums/topic/if-repeater-field-has-1-rows-2-rows-etc/
Upvotes: 0
Reputation: 269
Using the help from Danjah and tweaking it.
I ended up with this, it works perfectly. Displays a static image if only one row and then displays a slider if more than one image.
<?php
$top_images = get_field('top_images');
$top_images_count = count($top_images);
if( $top_images_count > 1 ): ?>
<?php if( have_rows('top_images') ): ?>
<div class="full-img-slider">
<?php while( have_rows('top_images') ): the_row();
$image = get_sub_field('image');
?>
<img src="<?php echo $image; ?>">
<?php endwhile; ?>
</div>
<?php endif; ?>
<!-- Close full image slider -->
<?php else : ?>
<!-- If only have one image do the below -->
<?php if( have_rows('top_images') ): ?>
<?php while( have_rows('top_images') ): the_row();
$image = get_sub_field('image');
?>
<div class="content-area">
<img src="<?php echo $image; ?>">
</div>
<?php endwhile; ?>
<?php endif; ?>
<!-- Close full image slider -->
<?php endif; ?>
Upvotes: 1
Reputation: 1246
Add this around your existing code:
<?php
$top_images = get_field('top_images');
$top_images_count = count($top_images);
if ( $top_images_count > 1 ) {
//YOUR EXISTING CODE HERE
}
?>
Then you need to add an elseif rule to display a static image if just one image has been added.
} elseif ( $top_images_count == 1 ) {
//DISPLAY IMAGE
}
Read more her: https://www.advancedcustomfields.com/resources/code-examples/
Upvotes: 0