Advanced Custom Fields – Setting a default for unsaved true / false options

Yesterday I was implementing a true / false option using ACF and i came across a little problem. I needed to write an if statement like this…if the option equals true then display this html.

The problem is I need the html to display by default, i.e when someone first installs the theme before saving any options, but the option value remains empty until the options are saved for the first time.

After a little bit of thinking I realised that by using ACF function get_field_object() I could use default_value field. Great…problem solved? Hmm not quite…its not as simple as this as the default_value field also isn’t set until ACF options are first saved.

So to get around this you can use a PHP empty() function as part of the conditional like below. If the default_value field is blank then we know the options haven’t of been saved yet, which is just what we need to know. Bingo.

$option = get_field_object('option_name', get_the_ID());

if (empty($option['default_value']) || $option['value'] == true) {

}

Leave a Reply

Your email address will not be published. Required fields are marked *