1

We have the following register_setting() function from the Settings API:

register_setting( string $option_group, string $option_name, array $args = array() )

I get what the $option_name and the $args are. But I have forever struggled to understand the real purpose of the $option_group parameter. I still fail to see its use.

I know that it is used in both register_setting() and settings_fields() and that the value should match. I also understand it is some way to "group" our settings (but it has no effect on the database).

  1. How does it matter which string we use for this parameter?
  2. Do I really need to set this string to something original or could I just use a randomly generated string?
  3. What would happen if we all just left it as an empty string? How would that affect WordPress?

I have the feeling that it doesn't matter at all which value we use for this parameter as long as we use the same value for both functions.

Would the following code make sense? Assuming that each line of code was placed in the right place, with both functions having access to the variable.

$random_option_group = bin2hex(random_bytes(5));

register_setting( $random_option_group, 'my_option' );

settings_fields( $random_option_group )

Or is the content of $option_group a string that we should be able to know and remember? And if so, what for?

2 Answers 2

1

The $option_group parameter of register_setting should match the $option_group parameter of settings_fields, which is typically used as part of creating a custom settings page.

When you use register settings with register_setting(), your registered settings are added to a global variable of allowed options, where they are grouped by the $option_group parameter. When you submit your settings page WordPress only updates the options for $_POST fields that match options found in the list of allowed options for the current group. The current group is determined by a hidden field that's added by the settings_fields() function.

0

In the register_setting() docs it lists the option group keys that are allowed by default:

Default allowed option key names include 'general', 'discussion', 'media', 'reading', 'writing', and 'options'.

You are able to add new keys using add_allowed_options().

As to why: My understanding is that this allows WordPress to "know" about your settings, and allows them to be used in the context of the Settings API. You can, of course, define any kind of setting name you want, but if you want to leverage the management functionality of the Settings API, you should use an allowed option group 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.