Читать книгу Professional WordPress Plugin Development - Brad Williams - Страница 91
Defining Sections and Settings
ОглавлениеNow define what the settings will be more precisely by using the function add_settings_field()
and how they will be visually grouped with the function add_settings_section()
.
<?php add_settings_section( id, title, callback, page ); add_settings_field( id, title, callback, page, section, args ); ?>
The first function call, add_settings_section()
, defines how the section on the page will show. The four required parameters it uses follow:
id: HTML ID tag for the section
title: Section title text that will show within an <H2> tag
callback: Name of the callback function that will echo some explanations about that section
page: Settings page on which to show the section (that is, the ?page=pdev_plugin part of the page URL)
The second function call, add_settings_field()
, describes how to add the form input. Its required parameters follow:
id: HTML ID tag for the section
title: Formatted title of the field, which is displayed as the label for the field on output
callback: Name of the callback function that will echo the form field
page: Settings page on which to show the section
section: Section of the settings page in which to show the field, as defined previously by the add_settings_section() function call
args: Additional arguments used when outputting the field
Now let's implement these new functions for your plugin settings as follows:
<?php add_settings_section( 'pdev_plugin_main', 'PDEV Plugin Settings', 'pdev_plugin_section_text', 'pdev_plugin' ); add_settings_field( 'pdev_plugin_name', 'Your Name', 'pdev_plugin_setting_name', 'pdev_plugin', 'pdev_plugin_main' );
You now need to define two simple callback functions: one to display a few explanations about the section and one to output and fill the form field.
<?php // Draw the section header function pdev_plugin_section_text() { echo '<p>Enter your settings here.</p>'; } // Display and fill the Name form field function pdev_plugin_setting_name() { // get option 'text_string' value from the database $options = get_option( 'pdev_plugin_options' ); $name = $options['name']; // echo the field echo "<input id='name' name='pdev_plugin_options[name]' type='text' value='" . esc_attr( $name ) . "'/>"; }?>
This second function call fetches the option value name
that is stored in an array.
When outputting the HTML input field, note its name. This is how you tell the browser to pass this value back into an array with the same name as the option you'll save, as defined earlier in the register_setting()
function call. Any field that has not been previously registered and whitelisted will be ignored by WordPress.
You'll also notice you are using the esc_attr()
function. This is used to escape the HTML attribute value for display. You'll learn more about this in Chapter 4.