In: , , ,
On: 2009 / 05 / 05 Viewed: 47448 times
Shorter URL for this post: http://ozh.in/lp

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

PHP:
  1. add_action('admin_init', 'ozh_sampleoptions_init' );
  2. function ozh_sampleoptions_init(){
  3.     register_setting( 'ozh_sampleoptions_options', 'ozh_sample' );
  4. }

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:

PHP:
  1. // Draw the menu page itself
  2. function ozh_sampleoptions_do_page() {
  3.     ?>
  4.     <div class="wrap">
  5.         <h2>Ozh's Sample Options</h2>
  6.         <form method="post" action="options.php">
  7.             <?php settings_fields('ozh_sampleoptions_options'); ?>
  8.             <?php $options = get_option('ozh_sample'); ?>
  9.             <table class="form-table">
  10.                 <tr valign="top"><th scope="row">A Checkbox</th>
  11.                     <td><input name="ozh_sample[option1]" type="checkbox" value="1" <?php checked('1', $options['option1']); ?> /></td>
  12.                 </tr>
  13.                 <tr valign="top"><th scope="row">Some text</th>
  14.                     <td><input type="text" name="ozh_sample[sometext]" value="<?php echo $options['sometext']; ?>" /></td>
  15.                 </tr>
  16.             </table>
  17.             <p class="submit">
  18.             <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
  19.             </p>
  20.         </form>
  21.     </div>
  22.     <?php   
  23. }

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:

PHP:
  1. register_setting( 'my_options', 'your_age', 'intval' );

If you're allowing safe text with a limited set of HTML tags:

PHP:
  1. 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:

PHP:
  1. function ozh_sampleoptions_init(){
  2.     register_setting( 'ozh_sampleoptions_options', 'ozh_sample', 'ozh_sampleoptions_validate' );
  3. }
  4.  
  5. // Sanitize and validate input. Accepts an array, return a sanitized array.
  6. function ozh_sampleoptions_validate($input) {
  7.     // Our first value is either 0 or 1
  8.     $input['option1'] = ( $input['option1'] == 1 ? 1 : 0 );
  9.    
  10.     // Say our second option must be safe text with no HTML tags
  11.     $input['sometext'] =  wp_filter_nohtml_kses($input['sometext']);
  12.    
  13.     return $input;
  14. }

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

This entry "Handling Plugins Options in WordPress 2.8 with register_setting()" was posted on 05/05/2009 at 12:50 pm and is tagged with , , ,
Watch this discussion : Comments RSS 2.0.

38 Blablas

    Pages: [4] 3 2 1 » Show All

  1. 38
    Ozh France »
    thought, on 09/Dec/09 at 10:00 am # :

    Hikari » use delete_option() as usual. For code posting I use "ig syntax hiliter".

  2. 37
    Hikari Brazil »
    wrote, on 09/Dec/09 at 6:59 am # :

    Very interesting, I still didn't know about it!

    And I have a question, how about unstalling function? What is the best way of removing from database anything we created with

    CODE:
    1. register_setting()

    ?

    And what plugin do you use for this Posting code filter? :P

  3. 36
    Tony Dew Canada »
    replied, on 03/Dec/09 at 12:31 am # :

    Ozh: Thanks for yet another great tutorial. Very helpful!

    Ade: Yes, as a matter of fact, your tip on multiple sets of options was very helpful. Just what I needed, actually!

  4. 35
    Ozh France »
    commented, on 12/Nov/09 at 8:26 pm # :

    Lopo Lencastre de Almeida » So you did it wrong.

  5. 34
    Lopo Lencastre de Almeida Portugal »
    replied, on 12/Nov/09 at 6:02 pm # :

    I did it and with WP2.8.5 it says that it can't find options.php

  6. 33
    Brenton United States »
    commented, on 07/Nov/09 at 9:02 am # :

    I got it. Sorry for the question. Somehow, by writing out my question (and then reading my own post) I saw the answer. Hooking into the option filters under this new scheme (to use the example above) would simply be:

    add_filter('sanitize_option_ozh_sample', myFunction, 10, 2);

    myFunction() would then need to pick its way through the supplied array looking for 'option1' and then filter its value appropriately.

  7. 32
    Brenton United States »
    replied, on 07/Nov/09 at 8:53 am # :

    I'm all for consolidating multiple plugin-related settings into one (wp_options) database entry using the method suggested above, except for detail. None of the filter functions or sanitize functions appear to work because the name of the option is no longer just "option1" (to use your example above) but is now "ozh_sample[option1]". How can you register this new name with a filter? Previously you would use:
    add_filter('sanitize_option_option1', myFunction, 10, 2);
    but the new approach would require:
    add_filter('sanitize_option_ozh_sample[option1]', myFunction, 10, 2);
    which doesn't appear to work.

    Any ideas?

  8. 31
    WebDev Germany »
    thought, on 31/Oct/09 at 12:08 pm # :

    Thanks in advance :) I'm collecting useful Wordpress plugin development techniques to my upcoming Twitter plugin. I've found lots of cool information in your blog!
    Thank you!

Pages: [4] 3 2 1 » Show All

Leave a Reply

Comment Guidelines or Die

  • HTML: You can use these tags: <a href=""> <em> <i> <b> <strong> <blockquote>
  • Posting code: Post raw code (no <> &lt; etc) within appropriate tags : [php][/php], [css][/css], [html][/html], [js][/js], [sql][/sql], [xml][/xml], or generic [code][code]
  • Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar.
  • Spam: Various spam plugins on patrol. I'll put pins in a Voodoo doll if you spam me.
  • I will mark as Spam test comments, all comments with SEO names (ie "My Cool Online Shop" instead of "Joe") or containing forum-like signatures.

Read more ?

Close
E-mail It