Whenenver you do get_option( 'my_option' )
and that my_option
is literally False
itself, you cannot simply check for if( !get_option( 'my_option' ) )
, to see if the value exists, because it'll return False
and the check will be meaningless.
Is there no way to check whether or not the option key my_option
exists?
Whenenver you do get_option( 'my_option' )
and that my_option
is literally False
itself, you cannot simply check for if( !get_option( 'my_option' ) )
, to see if the value exists, because it'll return False
and the check will be meaningless.
Is there no way to check whether or not the option key my_option
exists?
1 Answer
Reset to default 3You can set a default value for when the option does not exist. This way you can check to see if the returned value is false, or if it doesn't exist at all:
$value = get_option( 'my_option', $default_value );
if( $value == $default_value ) {
// Option does not exist
} elseif ( $value == false ) {
// Option's value is equal to false
}
'my_option'
wouldn't literally be false, because booleans don't get stored in the database.update_option( 'my_option', false );
will save a value of'0'
, notfalse
. So if you want to check if a value doesn't exist at all, do a strict check for=== false
. – Jacob Peattie Commented Oct 31, 2019 at 14:50False
and it doesn't even save anything, not0
...just nothing. The documentation forupdate_option
specifies that the item must be serializable if it's non-scalar. Bools are scalars, so, it should handle the serialization...yet, if I savefalse
, it doesn't get saved, if I savetrue
, it gets converted to1
. When I read: core.trac.wordpress/ticket/40007 / it seems thatget/update_option
is really messed up and I should just rely on0/1
to do my checks. – Daniel Smith Commented Nov 1, 2019 at 11:19