Subtleties of get/update_option: how to handle unpredictable results when dealing with booleans?


What update_option does should be simple: save any serializable value to the database, and it does…but in a weird way.

Looking at, @subrataemfluence confirms this is the “save logic table” of update_option:

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'
'false' - works. Value added is 'false'

It seems it has issues with transforming false to 0 when saving, why? Well, when go into update_option to see what’s reallly going on, we find that it does a check ( ):

if ( $value === $old_value || maybe_serialize( $value ) === maybe_serialize( $old_value ) ) {
    return false;

I’ll save you the time. $old_value is, of course, False, because if you scroll up a bit, you see that it first tries to get the option you’re trying to add: $old_value = get_option( $option );, and what do we know? get_option returns False if it doesn’t find anything…and we’re trying to add False to the database

So, of course, it doesn’t even go past this. It automatically satisfies the first check $value === $old_value even if it’s not expected behavior.

I am 100% sure that there’s a billion subtle bugs in virtually everything that’s built with WP because of this but how to solve it?

How can I wrap around these 2 functions so I don’t run into subtle bugs?

As a side-note, I genuinely don’t understand why it returns False if the value wasn’t updated. Sure, there’s a performance consideration there but at the cost of introducing subtle bugs?

Daniel Smith 3 years 2019-11-01T06:40:07-05:00 0 Answers 95 views 0

Leave an answer