In the upcoming WordPress 2.8 there's an interesting function set meant to help authors manage their plugin custom options. In a nutshell: whitelist your options, define how you want them to be validated, and just lean back and rely on the API to handle everything for you.
Your new best friend is function register_setting(), and I'm going to recapitulate how it's supposed to be used.
The (very) old (deprecated) way (that sucks)
If you began coding plugin a long time ago, you may have sticked to the habit of doing everything yourself, re-inventing and re-coding the wheel everytime.
Does something like checking for $_POST on your plugin admin page ring a bell? Time to evolve to a hassle free way of coding stuff.
The (new) register_setting() way (that pwnz)
The concept is the following: do the little tasks, let WordPress manage the dirty job.
- on init, tell WordPress that you're going to use some new options
- optional but cool, tell WordPress what function you'd like to be used for data validation (the user is supposed to enter text on your plugin admin page? Make sure it's only text, then)
- optional but cool, store all your options in one DB entry (yeah, those who've been reading this blog for a while know that it's my favorite pet peeve)
- don't handle POST data, let WordPress do it
- don't update/create the DB entry in the options, let WordPress do it
- don't bother with all the security, nonces, anti XSS stuff you have to throw in, let WordPress do it
Code, dissected
First, tell WordPress that you're going to use new options
-
add_action('admin_init', 'ozh_sampleoptions_init' );
-
function ozh_sampleoptions_init(){
-
register_setting( 'ozh_sampleoptions_options', 'ozh_sample' );
-
}
This function says: I'm going to need a new set of options, named 'ozh_sampleoptions_options', it will be stored in the DB entry 'ozh_sample'. There can a third parameter, a callback function to sanitize data: we'll see this later.
Then, we need to draw the plugin option page itself. Nothing really new here, except just one new thing. The function that echoes the admin form would be something like:
-
// Draw the menu page itself
-
function ozh_sampleoptions_do_page() {
-
?>
-
<div class="wrap">
-
<h2>Ozh's Sample Options</h2>
-
<form method="post" action="options.php">
-
<?php settings_fields('ozh_sampleoptions_options'); ?>
-
<?php $options = get_option('ozh_sample'); ?>
-
<table class="form-table">
-
<tr valign="top"><th scope="row">A Checkbox</th>
-
<td><input name="ozh_sample[option1]" type="checkbox" value="1" <?php checked('1', $options['option1']); ?> /></td>
-
</tr>
-
<tr valign="top"><th scope="row">Some text</th>
-
<td><input type="text" name="ozh_sample[sometext]" value="<?php echo $options['sometext']; ?>" /></td>
-
</tr>
-
</table>
-
<p class="submit">
-
<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
-
</p>
-
</form>
-
</div>
-
<?php
-
}
Notice the settings_fields() call. This tells WordPress to add all the hidden fields our form needs (nonce, referrer check...), and that we're going to use our option set previously defined as 'ozh_sampleoptions_options'.
And that's all, basically. You don't need to check if user submits the form, to check whether the options need to be updated or not, to handle things passed to $_POST. WordPress takes care of it.
Data sanitization
Function register_setting() accepts 3 parameters: the option group name, the option name to save and sanitize, and a callback function that does the sanitization.
If you want the user to submit integers, and only integers (say, they age), you would for instance use:
-
register_setting( 'my_options', 'your_age', 'intval' );
If you're allowing safe text with a limited set of HTML tags:
-
register_setting( 'my_options', 'your_bio', 'wp_filter_nohtml_kses' );
Now, in the previous example, since we want to store everything in a single DB entry, we'll define our own validation function:
-
function ozh_sampleoptions_init(){
-
register_setting( 'ozh_sampleoptions_options', 'ozh_sample', 'ozh_sampleoptions_validate' );
-
}
-
-
// Sanitize and validate input. Accepts an array, return a sanitized array.
-
function ozh_sampleoptions_validate($input) {
-
// Our first value is either 0 or 1
-
$input['option1'] = ( $input['option1'] == 1 ? 1 : 0 );
-
-
// Say our second option must be safe text with no HTML tags
-
$input['sometext'] = wp_filter_nohtml_kses($input['sometext']);
-
-
return $input;
-
}
All wrapped up
For your convenience, you'll find all the code of this article in the following plugin: ozh-sampleoptions-plugin.php (rename as .php)
Happy coding!
Related posts
Shorter URL
Want to share or tweet this post? Please use this short URL: http://ozh.in/lp
Metastuff
58 Blablas
Pages: [6] 5 4 3 2 1 » Show All
Pages: [6] 5 4 3 2 1 » Show All
replied, on 23/Aug/10 at 7:19 pm # :
@Ozh: you are a life-saver. never would have found that!
said, on 23/Aug/10 at 6:22 pm # :
darrinb » look at function add_settings_error()
said, on 23/Aug/10 at 5:33 pm # :
does anyone know how to incorporate an error message using register_setting()? I have a callback function that checks to see if a value of an option already exists and if so, prevents the user from overriding it. I can prevent the override, but I can't display an error message. Additionally, WP shows the "settings saved" message.
This is the code:
replied, on 31/Jul/10 at 3:01 pm # :
even after reading the post and going through the sample options , i still cant retrieve the options. I am using the example to make my theme options using settigns api, how do i retrieve it? Somebody please help. :(
commented, on 10/Jul/10 at 4:55 pm # :
How can we handle a select tag with the ability to select multiple items using the register_setting() ?
said, on 19/Apr/10 at 1:06 am # :
Francesco, an option entry can hold a unique option or an array, array is serialized automatically by WordPress.
OZH's exemple is great, because it teaches us how to hold a bunch of options in a unique array and submit it as POST automatically.
register_setting() is meant to allow WordPress to handle options saving from admin pages automatically. If we didn't do it as in his exemple, we'd need to add a function to convert different variables into a single array to be stored, which would make it much less automatic.
When you have a bunch of options, always try to store them in array, instead of creating a bunch of wp_options entries and using a SQL query for each of them.
commented, on 19/Apr/10 at 12:30 am # :
Nice article, but there is a thing I don't get it. In the wordpress codex reference, it does this example:
register_setting( 'my_options_group', 'my_option_name', 'intval' );
my_option_name looks a scalar here to me, hence the intval used to sanitize.
In your article you use an array instead. Doesn't it make the pourpose of register_setting less powerfull? You're compacting a lot of settings inside an only one setting that wordpress is aware of.
replied, on 17/Apr/10 at 5:40 pm # :
@Kaibone Thanks for your prompt reply. I really appreciate your help, but somehow it didnt worked. But it showed me a direction though.
the register_setting() method creates a new entry in db. No value parameter is attached to this method.
What i did was to loop through the $_POST array and use update_option in that loop. Like
This worked. Thanks alot for your help.
Regards.