What's the benefits between the two methods of displaying a ACF field

So I have a very simple ACF field which displays an introduction. Let’s say it’s added to the theme:

<section class="introduction">
    <?php the_field('introduction'); ?>
</section>

Now if there’s no field found for introduction it won’t be implemented, but the HTML tags will remain in the DOM.

Or we could implement it like so:

<?php $introduction = get_field('introduction'); ?>
    <?php if($introduction) { ?>

  <section class="introduction">
    <?php echo $introduction; ?>
  </section>
  
  <?php } ?>

Which will check first if there is a field, and if there is, display the appropriate HTML and field data.

What option would you take when building a theme? Is it best practice to take the second option, or is it not worth writing the extra code each time?

1 Like

Hi Peter,

As you say, the first option will result in an empty tag appearing in the page markup. Sometimes this isn’t a problem, but there may be situations where the styling of the empty element will still make it visible on the page even if there isn’t any content.

You might also have other logic within the template that depends upon the value of the custom field, in which case you’d need to go with the second option.

1 Like

Thanks fretburner. So I guess it really is best to judge as I go whether it’s OK to have an empty tag or if it would be safer to use the second option.

It’s just one of those things, I’ve used the first option for such a long time, I’m really starting to examine the way I code and figuring out if what I’m doing really is the best option or not.

Thanks again. :smile: