How can I include a setting that has a variable number of values in a settings page using register_setting?

If you are using the Settings API correctly, you should be using the add_settings_field function. The 3rd argument in this function is for the callback function that will generate the HTML for the form field for the individual setting. The Codex states:

Function that fills the field with the desired inputs as part of the
larger form. Name and id of the input should match the $id given to
this function. The function should echo its output.

In this callback function, you just write your HTML, just like you would if WordPress was not involved. As such, you can setup radiobuttons, a select field, multi-select, etc.

As an example, let’s say that you use add_settings_field as such:

add_settings_field(
    'my_setting_name',
    'My Setting Name',
    'my_setting_callback_function',
    'general',
    'my_settings_section_name'
);

In this snippet, the callback function named “my_setting_callback_function” will generate the HTML for the setting. You can then do something like:

function my_setting_callback_function() {
?>
    <select name="my_setting_name" id="my_setting_name">
        <option value="1">Enabled</option>
        <option value="0">Disabled</option>
    </select>
<?php
}

As you can see, this function generates the different possible values for this setting.

I highly encourage reading this part of the Codex: http://codex.wordpress.org/Settings_API. It does a nice job explaining the Settings API and the example does a good job illustrating how to use it. I find that the API is a bit convoluted; however, it does what it says it should do, so with a little discipline and careful checking, it should work quite well for you.

Good luck!

Leave a Comment