I'm trying to run a section of code based on whether a field is populated, but it's not working because I'm executing PHP inside the first PHP set, but I don't know how to do this.
The section called "social_media" is an Advanced Custom Fields repeater field. The number 7 is the page ID that this ACF field group is assigned to. I have a checkbox on the page that allows the site owner to decide if they want to show icons or not.
<?php if (get_field ('show_social_media_icons_at_the_top',7)): ?>
<?php while( have_rows('social_media',7)): the_row();
$icon = get_sub_field('social_media_icon');
$label = get_sub_field('social_media_label');
$link = get_sub_field('social_media_link');
?>
<div class="top-social-icon"><a href="<?php echo $link; ?>" target="_blank"><img src="<?php echo $icon; ?>" alt="<?php echo $label; ?>"></a></div>
<?php endif; ?>
Andrea P answers:
the ACF checkbox field is stored into an array.
so if you have only one option for that checkbox, and its value is, by instance, "yes", your code should be like this (I broke down the passages so it's clearer for you to understand how it works and use it in future works):
<?php
$show_social_icon_field = get_field ('show_social_media_icons_at_the_top',7);
$show_social_icon = $show_social_icon_field[0];
if ($show_social_icon=="yes"): ?>
<?php while( have_rows('social_media',7)): the_row();
$icon = get_sub_field('social_media_icon');
$label = get_sub_field('social_media_label');
$link = get_sub_field('social_media_link');
?>
<div class="top-social-icon"><a href="<?php echo $link; ?>" target="_blank"><img src="<?php echo $icon; ?>" alt="<?php echo $label; ?>"></a></div>
<?php endwhile; ?>
<?php endif; ?>
Kyler Boudreau comments:
Andrea - thank you for breaking that down. I really appreciate the help!
Arnav Joy answers:
are you using repeater field? if yes then please check this
http://www.advancedcustomfields.com/resources/repeater/
Dbranes answers:
Notice that <em><?php endwhile; ?></em> is missing from your code snippet, just above <em><?php endif; ?></em>
You could also peek into the post meta with:
var_dump( get_field ('show_social_media_icons_at_the_top',7) );
if you're not sure what it contains.