Hi there,
I’m using a layout consisting of two textfields and a text area field within a flexible field group.
When I use the above mentioned layout multiple times without adding value to one of the fields, the blank fields are displaying the previous groups records: If I add a title to the first occurrence but leave it blank at the second, the second group will display the title saved at the first.
What am I missing?
<?php
if( have_rows('content') ):
while ( have_rows('content') ) : the_row();
if ( get_row_layout() == 'textblock' ):
if( get_sub_field('title') ):
$title = get_sub_field( 'title' );
endif;
if( get_sub_field('lead') ):
$lead = get_sub_field( 'lead' );
endif;
if( get_sub_field('body') ):
$body = get_sub_field( 'body' );
endif;
?>
<section class="textblock">
<?php echo $title ?>
<?php echo $lead ?>
<?php echo $body ?>
</section>
<?php
else :
endif;
?>
<?php
endif;
endwhile;
endif;
?>
This is not an error in the flex field, but in your logic. You are only setting a new value for the 3 variables if the field has a value, but you not resetting or unsetting the previous value it in the next iteration of the loop.
<?php
if( have_rows('content') ):
while ( have_rows('content') ) : the_row();
if ( get_row_layout() == 'textblock' ):
$title = '';
if( get_sub_field('title') ):
$title = get_sub_field( 'title' );
endif;
$lead = '';
if( get_sub_field('lead') ):
$lead = get_sub_field( 'lead' );
endif;
$body = '';
if( get_sub_field('body') ):
$body = get_sub_field( 'body' );
endif;
?>
<section class="textblock">
<?php echo $title ?>
<?php echo $lead ?>
<?php echo $body ?>
</section>
<?php
else :
endif;
?>
<?php
endif;
endwhile;
endif;
?>
Thanks for the comment and explanation, it does work as intended.