Home › Forums › General Issues › 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 } ?>
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; ?>
The topic ‘Display if not empty’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.