Skip to content
Advertisement

ACF if statement not working when field is empty

I have an ACF field for hero images called hero_image. This field sits at the top of my single.php page like so:

JavaScript

I’m using the $post_id variable to fetch the field from outside the loop. The image loads as expected.

If an image hasn’t been uploaded for a post using the field, I’m expecting there to be no markup on the front-end. However, I still see the following:

JavaScript

Why isn’t my if statement working when the field isn’t in use?

Advertisement

Answer

I did some further digging and found my problem.

I have two ACF fields hero_image and thumbnail_image. These are set to appear on all pages and posts including custom post types.

Looking at the header.php file, here’s what I found:

JavaScript

As you can see, I’m also using the variable $post_id outside the loop. This prevented the second $post_id variable working via single.php.

I’ve renamed $post_id in header.php to $post_id_outside_loop. I’ve then used this variable via single.php as it’s also outside the loop. This has solved the issue.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement