WordPress Options

I’ve been working on a project that involves reimplementing a site in WP. This specific setup requires quite a bit of custom logic, including several dozen options. It’s interesting work, and I feel I’m really stretching myself as a WordPress developer.

I’ve been working on a project that involves reimplementing a site in WP. This specific setup requires quite a bit of custom logic, including several dozen options. It’s interesting work, and I feel I’m really stretching myself as a WordPress developer.

Options in WordPress are easy to do. My first exposure to them was from looking at various themes’ options, but when you get right down to it they’re very simple. It all comes down to three little self-explanatory functions, that may be used anywhere in a theme:

set_option('option name','option value');
get_option('option name');
delete_option('option name');

That’s it, that’s all you really need. Now, a good theme or plugin will put in a lot of extra logic to make options pages nice and user-friendly. For instance, Erudite will structure options in a multi-level array, like so

$erdt_options = array (

	array(	"name" => __('Dark Colour Scheme','erudite'),
			"desc" => __("For all the dark colour lovers out there",'erudite'),
			"id" => $shortname."color_dark",
			"std" => "false",
			"type" => "checkbox"),

…and so on. Each field has a name, a description, a type (for the options screen), an id (used to retrieve and store the option) and a default value (“std”), for when a user wants to reset a theme. All of these are completely optional and depend on how the developer wants to built the options page. Unlike Drupal, there doesn’t seem to be a standard API.

The code might look something like this (again, taken from the Erudite theme):

foreach ($erdt_options as $value) { 
  switch ( $value['type'] ) {
    case 'text':
    // display one text field
    case 'select':
    //display a dropdown
  }
}

And to display one field:

<input name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_option( $value['id'] ) != "") { echo get_option( $value['id'] ); } else { echo $value['std']; } ?>" />
        <?php echo __($value['desc'],'erudite'); ?>

As you can see, each input field has its own ID, in case you want to do a bit of styling. Personally I would also add a general class to cover all fields, or maybe different classes for different types.

Saving these options is also quite simple:

foreach ( $erdt_options as $value ) {
  if ( isset( $_REQUEST[ $value['id'] ] ) ) { 
    update_option( $value['id'], $_REQUEST[ $value['id'] ]  );
  } 
  else {
    delete_option( $value['id'] );
  }
}

I’m ignoring all questions of where all this code fits in the functions.php file, where to place options pages in the admin section. That’s a topic for another day; I’m just going through the basics for my own benefit, and that of anyone who reads this.