Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

CHAPTER 7 • Making the Most of WordPress Plugins 191


<?php do_settings_sections( 'smashings_settingsdemo' ); ?>
<?php submit_button(); ?>



<?php
} // Back to PHP


This is the entire settings page markup — a really simple one that you’ll want to expand to
make it look good. Note settings_fields(), which points to a settings field created with
add_settings_field() called smashings_settingsdemo, and dosettings
sections(), which calls a section with the same name. There’s no need to create your own
submit button either to save these settings; submit_button() will do that for you.


Next, whitelist your settings and use add_settings_section() to add a settings section
and add_settings_field() to add an input field:


// Whitelist the settings
function smashings_settingsdemo_init(){


// Add the section
add_settings_section('smashing_settings_section',
'Smashing Settings',
'smashing_settings_section_callback',
'smashings_settingsdemo');


// Add settings field
add_settings_field('smashing_sample_input',
'Input sample',
'smashing_sample_input_callback',
'smashings_settingsdemo',
'smashing_settings_section');


// Register settings
register_setting( 'smashings_settingsdemo', 'smashing_sample_input',
'smashing_settingsdemo_validate' );


}


// Initiate smashings_settingsdemo_init() in admin
add_action( 'admin_init', 'smashings_settingsdemo_init' );


This isn’t too complicated, actually. First you create a section, smashing_settings_section,
with add_settings_section(). You’ll recognize smashings_settingsdemo, which is
the $page parameter. This is what you called for previously, in your settings page markup, with
do_settings_sections(). You connect the smashing_sampleinput settings field to
the newly created settings section with the final parameter, $section, by passing smashing

settings_section. For a full list of parameters for add_settings_section() and
add_settings_field(), refer to the Codex at http://codex.wordpress.org/
Function_Reference/add_settings_section and http://codex.wordpress.
org/Function_Reference/add_settings_field, respectively.

Free download pdf