190 PART III • Using Plugins with WordPress
I will, however, tell you how to use the Settings API (you can find more information at
http://codex.wordpress.org/Settings_API) to let WordPress take care of your
necessary data saving. This not only saves you a lot of time, but it also means that you will have
a solid base when it comes to security because WordPress takes care of things such as nonces.
Put it to the test by creating a simple settings page under Settings in the left admin menu that
stores two values: a text field and check box (which obviously is checked or not).
First, you need to create a plugin; it’ll be a single PHP file called smashing-settings.php,
starting with this:
<?php
/*
Plugin Name: Smashing Settings
Plugin URI: http://tdh.me/wordpress/smashing-settings/
Description: A simple settings plugin.
Author: Thord Daniel Hedengren
Author URI: http://tdh.me/
*/
Moving on, you need to add the Settings page to the menu by hooking a function on to
admin_menu. For this example, you’ll use add_options_page(), but there are other
options as well:
// Add the settings page function to the menu
add_action( 'admin_menu', 'smashings_settingsdemo_add_page' );
// Add to the menu
function smashings_settingsdemo_add_page() {
add_options_page( 'Smashing Sample Settings',
'Smashing Settings',
'manage_options',
'smashings_settingsdemo',
'smashings_settingsdemo_do_page' );
}
With add_options_page(), you create a page called Smashing Sample Settings, shortened
to Smashing Settings in the left admin menu. This is available only to users that have the
manage_options capability, has the unique ID of smashings_settingsdemo, and calls
a page with the function smashings_settingsdemo_do_page(). You need to create
that last function, so do that next:
// Add the actual settings page
function smashings_settingsdemo_do_page() {
// Leaving PHP for a while ?>
<h2>Smashing Settings</h2>
<p>This is our settings page.</p>
<form action="options.php" method="post">
<?php settings_fields( 'smashings_settingsdemo' ); ?>