Home Forums General Issues Display if not empty


Display if not empty

  • This is probably a really simple PHP problem on my part (still learning PHP), and I apologize that this probably isn’t an ACF issue more but rather my not knowing enough PHP, but I don’t understand why this isn’t working.

    I have a var for an Organization’s county, but I only want to display it if it is not empty (it’s an optional field, it’s not applicable to all Organizations).

    $org_county = get_field('county');
    function the_county_org() {
      if (!empty($org_county)) {
        echo $org_county . " County";

    Thanks for helping a noob.

    Update: Included my county var as an argument for the function. It displays correctly now on individual pages, but on the archive page for this custom post type, it does not display child posts.

  • Don’t think you need a function. Just do it like this in your template file:

    <?php if( get_field('county') ) { ?>
    	<?php echo get_field('county') . ' County' ; ?>
    <?php } ?>
  • Thank you,

    I have a tendency to try to over-think things 🙂

  • Hahah happens to the best of us! Good luck with your project!

  • Also a descent touch if not overused (since it worsens readability) is to do:

    <?php if( $county = get_field('county') ) { ?>
    	<?php echo $county . ' County' ; ?>
    <?php } ?>

    That will only call to the get_field function once thus saving you some resources. However as I said some would argue that this is bad practise as it can be harder to read (for humans) especially when it gets more complicated with many if statements etc.

  • <?php 
    $image = get_field('image');
    if( !empty($image) ): ?>
    	<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
    <?php endif; ?>
Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘Display if not empty’ is closed to new replies.