Hi,
I got a Repeater field for adding files. I also made a div to show this.
When there is no files i want to hide it.
My problem is when a row is added to the repeater field but no file is attached the code i made doesn’t hide the div, it only hides it if there are no rows added to the repeater field.
Is there a way to see if the row is empty and hide my div?
Here’s my code so far:
<?php
if (get_field('repeater_field')):
if( have_rows('repeater_field') ): ?>
<div>
<h3>Title</h3>
</div>
<div class="box-atachment">
<?php
while ( have_rows('repeater_field') ) : the_row();
$atachment = get_sub_field('repeater_files');
$title = $atachment["title"];
$url = $atachment["url"];
if( $atachment ) { ?>
<a href="<?php echo $url_anexo; ?>"><?php echo $nome_anexo; ?></a><br>
<hr>
<?php
}
endwhile;
endif;
?>
</div>
<?php
endif;
?>
Thanks
There isn’t an easy way to accomplish what you’re doing.
One easy solution would be to make the field field required. This would prevent the user from adding a row without selecting a file.
The other option would be to loop through the repeater and store the values in an array and then loop over the array to create your output.
<?php
$files = array();
if (have_rows('repeater_field')) {
while (have_rows('repeater_field')) {
the_row();
if (get_sub_field('repeater_files')) {
$atachment = get_sub_field('repeater_files');
$title = $atachment["title"];
$url = $atachment["url"];
$files[] = '<a href="'.$url.'">'.$title.'</a>';
} // end if get_sub_field
} // end while have_rows
} // end if have_rows
// see if there is anything in files
if (!empty($files)) {
?>
<div><h3>Title</h3></div>
<div class="box-atachment">
<?php
foreach ($files as $file) {
echo $file,'<br /><hr />';
}
?>
</div>
<?php
} // end if files !empty
?>
Hi, Thanks!
Your code worked fine. In my case making the field required wouldn’t work beacuse its optional.