
Previously we have gone over adding your own settings page and menu items. However, what if you just have a couple of options that hardly warrant a dedicated settings page? If your plugin’s options are relevant to one of the default WordPress settings pages, then it’s possible to add your own options to them.
We can accomplish this in one of two ways. If you have more than one option, you can first create a section to house all these options. If you have just one (or maybe two) options, you can just add the fields. We’ll start out by taking a look at the add_settings_section() function, which will allow us to add a section to a settings page.
[code='php']add_settings_section( $id, $title, $callback, $page );[/code]
- $id – Unique id for your section (don’t use any spaces)
- $title – The title of your section
- $callback – A function that will be run at the beginning of the section. Echo what you want to be there (such as a description of the settings)
- $page – The settings page this section will be going on (possible options include general, writing, reading, etc)
We’ll now look at the function for adding fields to the settings page. For this we use the add_settings_field() function.
[code='php']add_settings_field( $id, $title, $callback, $page, $section = 'default' );[/code]
- $id – A unique id for this field
- $title – The title of your option
- $callback – The function that will echo out the input field for this option
- $page – The settings page you want this option to appear on (eg. general, writing etc)
- $section – If you’ve setup your own section, name the id of it here, otherwise use default
Once we have our fields done, we need to register our options. We do this so that WordPress will handle updating the option in the database once the user presses submit. For this we’ll use the register_setting() function.
[code='php']register_setting( $option_group, $option );[/code]
- $option_group – A group for all your options. Give it a unique name, no spaces.
- $option – The name of the input for your option.
These functions will need to be hooked into the admin_init hook. Let’s take a look at a quick example where we add an option to the General settings page.
[code='php']function banana_service_init() {
add_settings_field( 'banana_service_key', 'Your Banana Service API Key', 'banana_service_key_form', 'general', 'default' );
register_setting( 'banana_service', 'banana_service_key' );
}
add_action( 'admin_init', 'banana_service_init' );
function banana_service_key_form() {
echo '
';
}[/code]
There you have it, an option field added to the General settings page.




