Registering Options

For the purposes of this chapter, Simplex Flex has four options: width (fixed or flexible), columns (two or three, and in which order), whether the site title and description will be shown in addition to the custom header image, and an option to manually enter additional CSS rules.

You'll have to register your option with WordPress or it won't get saved. You should also set some default values. For now, I'll just mention which lines are essential in order to get your options saved and updated correctly in the database.

Listing 7-29 shows the expanded function; it now registers your settings and creates some default values. The changes from the previous listing are in bold. You store all four theme options in a single database field by using an array. This is the best practice for saving theme and plugin options; it's bad form to use a separate database field for each of your options.

Listing 7-29. Registering a setting and saving the default values function simplex_menu() {

add_theme_page('Simplex Flex Options', 'Simplex Options', 'edit_theme_options',

register_setting('simplex_options', 'simplex_options'); // set defaults $options = array(

'width' => 'fixed', 'cols' => '3', 'sitename' => 'yes', 'css' => '',

add option('simplex options', $options, '', 'yes');

add_action('admin_menu', 'simplex_menu');

The register_setting() function shown here has two arguments. First, you have to assign your setting to a group. When you begin building the form, you call each group in turn. In this case, since you have just a few options, you use just one group, with the same name as the option itself. The second argument is the name of the option that will be stored to the database.

Once you registered the setting, you need to save some default values. You create the $options array to hold the four values. Then you can use the add_options() function to store your array. The first argument is, again, the name of the option field in the database. The second argument is the array containing the options to be stored. The third argument should always be empty; it's a deprecated argument that's still present for backward compatibility. The fourth argument, the autoload value, determines whether or not these options will be cached on each page load. This should almost always be "yes."

Was this article helpful?

0 0

Post a comment