当我使用注册布尔设置时register_setting() 我已传递数据类型:
register_setting(
option_group: \'…\',
option_name: \'…\',
args: [
\'type\' => \'boolean\',
\'description\' => \'…\',
\'sanitize_callback\' => function (mixed $value): bool {
return (bool) $value;
},
\'show_in_rest\' => false,
\'default\' => false,
],
);
但是,调用选项时
get_option(), 它仍然会返回一个字符串值:
"1"
我想将值与
=== 并希望避免以下情况:
(bool) get_option(\'…\') === true
以及
boolval(get_option(\'…\')) === true;
我正在考虑创建一个助手函数,它的作用类似于代理,检查给定选项名称的设置的数据值,相应地转换它并返回它。
类似于:
/**
* Get option with a value converted into the correct data type as registered with `register_setting()`.
*/
public static function getOption(string $optionName): mixed
{
$optionValue = get_option($optionName);
$settingArgs = get_setting_args($optionName); // ???
if (empty($settingArgs[\'type\'])) {
return $optionValue;
}
switch ($settingArgs[\'type\']) {
case \'string\':
return (string) $optionValue;
case \'int\':
return (int) $optionValue;
case \'bool\':
return (bool) $optionValue;
case \'array\':
return (array) $optionValue;
case \'object\':
return (object) $optionValue;
case \'float\':
return (float) $optionValue;
default:
return $optionValue;
}
}
在代码中标记为
??? 我不知道如何访问WordPress中注册设置的参数。我该怎么做?还是应该以另一种方式实现我的目标?