0
votes

Fair warning, I'm a PHP noob. First post too :)

At the moment I have a ACF group with 3 subfields. I want to loop through these subfields and echo their 'label' and 'value'. If the subfield is empty, then I'd like the loop to skip/not echo the value. I can mimic the out with the the follow:

<?php
$objective_desc = "objective_desc";
$objective = get_field_object($objective_desc);
?>

 <div class="item">
        <?php if ( $objective_desc ): ?>
            <h2 class="sub-sample-title"><?php echo $objective['label']; ?></h2>
        <?php endif; ?>

        <?php if ( $objective_desc ): ?>
             <p class="sub-description"><?php echo $objective['value']; ?></p>
        <?php endif; ?>
</div>

The problem is that I'd have to copy and past for every subfield in the group. Im sure there's a more elegant way of doing it.

2

2 Answers

0
votes

I think you've got a typo in the code you posted; you probably mean to check if the "subfields" are empty by checking <?php if ( $objective_label ): ?> instead of <?php if ( $objective_desc ): ?>, right? If you're just checking to see if $objective_desc is empty every time, you can do it all within one if block.

Be careful about using empty if statements to check if a variable is empty. You should use empty instead: <?php if ( empty($objective_desc) ): ?>. In your code, you set $objective_desc up top, so it will evaluate as true even if there's nothing in it.

There's probably some convoluted way you can setup loops and extra variables to make it more "elegant", but since you're changing other HTML elements based on the subfield (<h2>, <p>, etc), honestly, you're better off copy-and-pasting into a bunch of if statements. It'll be clearer, work just as fast, and be easier to debug. My two cents.

0
votes

I think if you're looking to loop through the group sub fields, I've found a solution. Say for example, you want to loop through a group which contains a bunch of links and their respective text. You simply do this:

            <?php $links = get_field('list_of_links'); ?>
            <ul>
                <?php foreach ($links as $link) {
                    if (!empty($link)): ?>
                        <li><a href="<?php echo $link['url'] ?>"><?php echo $link['title'] ?></a></li>
                <?php endif; } ?>
            </ul>