WordPress issue with get_option and update_option when passing false in $value parameter
Answer a question
I have encountered a strange issue with get_option and update_option. I was in need of adding an option to wp_options table so I used this
update_option('_option_key_index', false), but this never adds a record in the database. But if I pass update_option('_option_key_index', 0) the record gets added.
Further inspection of the core function update_action reveals something strange. The value false is actually being treated as an empty string, whereas true is not! So when I am passing false for a key which I know does not exist in yet, get_option returns an empty string ($old_value = get_option( $option );), which when being compared in the following snippet:
if ( $value === $old_value )
return false;
always returns false and hence no record is being added to the database!
The question is why WordPress is treating the Boolean value false as an empty string while it is not same for value true ?
Below is a list of values I tried with and the results I got:
true: works. Value added is 1
1: works. Value added is 1
false: does not work - No record added
0: works - Value added is 0
'true': works. Value added is true (passed as string)
'false': works. Value added is false (passed as string)
Answers
When PHP casting boolean as a string, false become '' (empty string) while true become '1' (string).
Since WordPress is PHP-based, you may need to stick to 1/0 or true/false (as a string) to differentiate a 'boolean'.
更多推荐
所有评论(0)