I have a tricky bug in a plugin and I'm trying to figure out who's fault it is.
The plugin uses in its init method a check if the DB has to be updated. And the child theme I'm using has set a custom local with setlocal()
. As a result get_option()
return a string instead of a float value.
Here is the basic setup how to reproduce the error:
// set custom local
setlocale(LC_ALL, 'de_DE.UTF-8');
// set current DB version
update_option("db_version", 5.39);
// get DB version
$db_version = get_option("db_version"); // (string) 5,39
// Update DB if necessary
if(!empty($db_version) and $db_version < 5.13) {
$wpdb->query("ALTER TABLE example CHANGE `cat_id` `cat_ids` VARCHAR(255) NOT NULL DEFAULT ''");
}
As the update is already in the system it throws an error as ((string) "5,39" < 5.13) === true
.
Test the PHP behavior
I wrote a little check up for me to see what causes the error:
<?php
setlocale(LC_ALL, 'de_DE.UTF-8');
echo '<pre>';
$locale_info = localeconv();
echo 'decimal_point=' . $locale_info['decimal_point'] . "\n"; // decimal_point=,
// Test like the DB update check in WP
$db_version = floatval('5.39');
if(!empty($db_version) and $db_version < 5.13) // <==
echo "ERROR $db_version is not smaller than 5.13";
else
echo "SUCCESS $db_version > 5.13";
?>
I was surprised by the output:
SUCCESS 5,39 > 5.13
If I interpreted my testing correct, PHP reads the decimal values correct and compares them correctly even after the locale
has changed. But as WP seems to ignore the case that the decimal point has been set to a comma value and returns just a string value when using get_option("db_version")
.
Question
Is DB update check
if(!empty($db_version) and $db_version < 5.13)
of the plugin wrong or is it wrong to usesetlocale()
for a WP project?Any good recommendation how to solve this issue?