1

When I register a boolean setting using register_setting() I already pass the data type:

        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,
            ],
        );

However, when calling the option with get_option(), it still returns me a string value:

"1"

I would like to compare values with === and would like to AVOID something like:

(bool) get_option('…') === true

AND

boolval(get_option('…')) === true;

I'm thinking of creating a helper function, that acts like a proxy, checks the data value of the setting for the given option name, convert it accordingly and return it.

Something like:

    /**
     * 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;
        }
    }

As marked in the code with ??? I have no idea to access the arguments of a registered setting in WordPress. How can I do so? Or should my goal be accomplished in another way?

1 Answer 1

4

The type argument is only relevant for the REST API and relatively new. If you want it to be enforced on get_option() you will need your own helper function, as you've noticed. This is probably for backwards compatibility reasons. I would avoid attempting to enforce this for all get_options() calls via a filter, and stick to using a helper function.

Registered settings are in the global $wp_registered_settings variable which you can retrieve with get_registered_settings(). The key of the array for your settings would be whatever you used for option_name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.