
I have all kinds of flexible content fields on my page and one of them is an anchor
field (example <div id="<?php echo sanitize_title(get_sub_field('anchor')); ?>"></div>
which is not the most clean way to do things I know), but if the anchor is being used on the page I want to create a navigation on the top of the page with all the anchors of that page. This loop looks something like this:
<div class="container">
<div class="row">
<div class="col-md-12">
<?php if( have_rows('flex') ): ?>
<?php while ( have_rows('flex') ) : the_row(); ?>
<?php if( get_row_layout() == 'anchor' ): ?>
<a href="#<?php echo sanitize_title(get_sub_field('anchor')); ?>" class="btn btn--fancy"><?php the_sub_field('anchor'); ?></a>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
</div>
</div>
</div>
But because there are always rows
in my flexible content it will always draw the container
and I want to check before the while
if a anchor
row is being used in this loop, so it only draws it when a anchor
is being used.
Any tips?
To do something like this you need to loop through the layouts first and gather the information and then loop over the gathered information to show the list
<?php
$anchors = array();
if (have_rows('flex')) {
while (have_rows('flex')) {
the_row();
if (get_row_layout() == 'anchor') {
$anchors[] = get_sub_field('anchor');
} // end if anchor
} // end whild have rows
} // end if have rows
if (count($anchors)) {
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<?php
foreach ($anchors as $anchor) {
?>
<a href="#<?php
echo sanitize_title($anchor); ?>" class="btn btn--fancy"><?php
echo $anchor; ?></a>
<?php
} // end foreach anchor
?>
</div>
</div>
</div>
<?php
} // end if anchors
?>