Registering Settings and Creating Defaults

Prior to version 2.7, you could create options without registering them with WordPress, but then you had to do a lot of manual security checks and updates. With the new settings API, all of that is much easier, but you must register your settings in order for them to work.

You may register a separate setting for each variable you need to store, but it's impolite to take up lots of database rows with your plugin's options. Instead, group your variables into arrays, each of which can be stored in a single database row. Listing 9-8 shows the code required to register a single setting. The first argument is the setting's name; the second is the name of the group in which it appears. In this case, you'll have just one group, so the names are the same.

Listing 9-8. Registering a setting function register_next_page_options() {

add_action('admin_init', 'register_next_page_options' );

Registering the setting lets WordPress know that you plan to use it, but it doesn't do anything about setting default values. You'll have to do that yourself. You can use the activation hook to make sure your options are set as soon as the plugin is activated. Listing 9-9 shows a function that sets default option values, stored in a single array, when the plugin is activated.

Listing 9-9. Setting default options on activation function next_page_activation() { // set defaults $options = array();

$options['before_prev_link'] = '<div class="alignleft">';

$options['prev_link_text'] = _('Previous:', 'next-page').' %title%';

$options['before_parent_link'] = '<div class="aligncenter">';

$options['parent_link_text'] = _('Up one level:', 'next-page').' %title%';

$options['before_next_link'] = '<div class="alignright">'; $options['next_link_text'] = __('Next:', 'next-page').' %title%'; $options['after_next_link'] = '</div>';

// set new option add_option('next_page', $options, '', 'yes');

register_activation_hook(_FILE_, 'next_page_activation');

The code here is fairly simple; it's just an array in which each element contains the default values for one of the options. Note the use of the add_option() function to save the options array to the database. The add_option() function requires four arguments:

• The name of the option to be saved

• An empty string (a deprecated argument kept for backward compatibility)

• The $autoload variable (This last argument determines whether your options should be loaded into WordPress' object cache on each page load. You'll be using these options in template files, so this value should be 'yes'.)

That's it! You've set the default values, and now it's time to build the form that will let you change those values.

0 0

Post a comment