Originally posted here: http://ottodestruct.com/blog/2009/wordpress-settings-api-tutorial/

When writing the Simple Facebook Connect plugin, I investigated how the Settings API worked. It’s relatively new to WordPress (introduced in version 2.7), and many things I read said that it was much easier to use.

It is much easier to use in that it makes things nice and secure almost automatically for you. No confusion about nonces or anything along those lines. However, it’s slightly more difficult to use in that there’s very little good documentation for it. Especially for the most common case: Making your own settings page.

So, here is my little documentation attempt.

Making your own settings page

First, add yourself an options page. Code to do that:

<?php // add the admin options page
add_action('admin_menu', 'plugin_admin_add_page');
function plugin_admin_add_page() {
add_options_page('Custom Plugin Page', 'Custom Plugin Menu', 'manage_options', 'plugin', 'plugin_options_page');
}
?>

What this does is quite simple, really:

a. It adds a link under the settings menu called “Custom Plugin Menu”.
b. When you click it, you go to a page with a title of “Custom Plugin Page”.
c. You must have the “manage_options” capability to get there though (admins only).
d. The link this will be will in fact be /wp-admin/options-general.php?page=plugin (so “plugin” needs to be something only you will use).
e. And the content of the page itself will be generated by the “plugin_options_page” function.

Oh wait, we need that function! Let’s go ahead and create that, shall we?

<?php // display the admin options page
function plugin_options_page() {
?>
<div>
<h2>My custom plugin</h2>
Options relating to the Custom Plugin.
<form action="options.php" method="post">
<?php settings_fields('plugin_options'); ?>
<?php do_settings_sections('plugin'); ?>

<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form></div>

<?php
}?>

Hang on a minute, where’s all the options? Well, here’s where the Settings API kicks in a bit. Up to now, this has been more or less the same as previous tutorials. Adding the options pages is really quite easy. But now, we’re going to use two new functions.

First, we call settings_fields(‘plugin_options’). This outputs the hidden bits that we need to make our options page both do what we want and to make it secure with a nonce. The string “plugin-options” can be anything, as long as it’s unique. There is another call we’re going to have to make with this same string later.

Next, we call do_settings_sections(‘plugin’). This is going to output all of our input fields. Text input boxes, radio fields, anything we like. Obviously though, we have to tell it what those fields are and look like somewhere. We do both of these things in the next section.

Defining the settings

<?php // add the admin settings and such
add_action('admin_init', 'plugin_admin_init');
function plugin_admin_init(){
register_setting( 'plugin_options', 'plugin_options', 'plugin_options_validate' );
add_settings_section('plugin_main', 'Main Settings', 'plugin_section_text', 'plugin');
add_settings_field('plugin_text_string', 'Plugin Text Input', 'plugin_setting_string', 'plugin', 'plugin_main');
}?>

Here we’ve done three things. Let’s break that down, shall we?

<?php register_setting( 'plugin_options', 'plugin_options', 'plugin_options_validate' );?>

First, we register the settings. In my case, I’m going to store all my settings in one options field, as an array. This is usually the recommended way. The first argument is a group, which needs to be the same as what you used in the settings_fields function call. The second argument is the name of the options. If we were doing more than one, we’d have to call this over and over for each separate setting. The final arguement is a function name that will validate your options. Basically perform checking on them, to make sure they make sense.

Ignoring the validation function for a moment, lets move on to the setting section. This one is actually quite simple.

<?php add_settings_section('plugin_main', 'Main Settings', 'plugin_section_text', 'plugin'); ?>

This creates a “section” of settings.
The first argument is simply a unique id for the section.
The second argument is the title or name of the section (to be output on the page).
The third is a function callback to display the guts of the section itself.
The fourth is a page name. This needs to match the text we gave to the do_settings_sections function call.

That function callback in the third argument should look a bit like this:

<?php function plugin_section_text() {
echo '<p>Main description of this section here.</p>';
} ?>

Simple, really. You can put any HTML you like here.

Now that we’ve talked about the section itself, we need to talk about the fields in that section.

<?php add_settings_field('plugin_text_string', 'Plugin Text Input', 'plugin_setting_string', 'plugin', 'plugin_main'); ?>

The first argument is simply a unique id for the field.
The second is a title for the field.
The third is a function callback, to display the input box.
The fourth is the page name that this is attached to (same as the do_settings_sections function call).
The fifth is the id of the settings section that this goes into (same as the first argument to add_settings_section).

The only difficult one here is, again, the callback. Let’s look at that, shall we?

<?php function plugin_setting_string() {
$options = get_option('plugin_options');
echo "<input id='plugin_text_string' name='plugin_options[text_string]' size='40' type='text' value='{$options['text_string']}' />";
} ?>

Simple. It just gets the options then outputs the input HTML for it. Note the “name” is set to plugin_options[text_string]. This is not coincidence, the name *must* start with plugin_options in our case. Why? Because that is the second argument we passed to register_settings.

The settings pages use a whitelist system. Only valid options get read. Anything else gets tossed out, for security. Here, we’re using a php trick. PHP interprets an incoming GET or POST data of name[thing] as being an array called name with ‘thing’ as one of the elements in it. So, all our options are going to take the form of plugin_options[some_thing], so that we get that single array back, and the array name itself is whitelisted.

Since this is designed with security in mind, we have one last callback to deal with: The validation callback that we skipped earlier:

<?php // validate our options
function plugin_options_validate($input) {
$newinput['text_string'] = trim($input['text_string']);
if(!preg_match('/^[a-z0-9]{32}$/i', $newinput['text_string'])) {
$newinput['text_string'] = '';
}
return $newinput;
}
?>

Here I’m taking a liberty with the code. I’m going to say that our text_string has to be exactly 32 alphanumerics long. You can actually validate any way you want in here. The point of this function is simply to let you check all the incoming options and make sure they are valid in some way. Invalid options need to be fixed or blanked out. Finally, you return the whole input array again, which will get automatically saved to the database.

Take special note of the fact that I don’t return the original array. One of the drawbacks of this sort of approach is that somebody could, in theory, send bad options back to the plugin. These would then be in the $input array. So by validating my options and *only* my options, then any extra data they send back which might make it here gets blocked. So the validation function not only makes sure that my options have valid values, but that no other options get through. In short, $input is untrusted data, but the returned $newinput should be trusted data.

Update: What if you have multiple options screens? Or just want to only be able to edit a few of your options? One downside of the validation method I detail above is that your single plugin_options field gets completely replaced by $newinput. If you only want to have it change a few of your options, then there’s an easy technique to do that:

<?php // validate our options
function plugin_options_validate($input) {
$options = get_option('plugin_options');
$options['text_string'] = trim($input['text_string']);
if(!preg_match('/^[a-z0-9]{32}$/i', $options['text_string'])) {
$options['text_string'] = '';
}
return $options;
}
?>

Basically I load the existing options, then update only the ones I want to change from the $input values. Then I return the whole thing. The options I don’t change thus remain the same.

And we’re done. Wait, what?

Yes, the whole point of this exercise is that the options are automatically saved for you. And everything else. You have an options page, you have fields on it, you are validating them… and that’s it. The actual *display* of the page is even done for you. Remember the input we made? It’ll get put into a table with the title on the left side before it, waiting for input.

Another nice thing is that this is easily expandable. For each option to add we:
1. Do a new add_settings_field call.
2. Make the function to display that particular input.
3. Add code to validate it when it comes back to us from the user.

To add a new section, you:
1. Do a new add_settings_section call.
2. Make the function to display any descriptive text about it.
3. Add settings fields to it as above.

One last thing

Sometimes we don’t need a whole page. Sometimes we only have one setting, and it would work well on some existing page. Maybe on the general page, or the discussion page. Well, we can add settings to those too!

If you look through the core code, you’ll find references like do_settings_sections(‘general’) or do_settings_sections(‘writing’), and so on. These you can add on to like any others, getting your settings on the main WordPress settings pages instead of having to make your own.

Just do this:
1. Make an add_settings_section call. The last argument should be “general”, or wherever you want to add your new section.
2. Add fields to your new section, using add_settings_field.
3. You still need to make your own settings whitelisted. To do this, you’ll need to make a call to register_setting. The first argument should be the same as the page name, like ‘general’, or wherever you’re putting your settings. This will let that page recognize and allow your settings to come through.

All the callbacks will basically be the same for this method. You’re just skipping a step of making your own page. Easy.

And there you go. More reading: http://codex.wordpress.org/Settings_API

Shortlink:

233 Comments

  1. Thanks for a great article!

    This was way more helpful than the actual WordPress documentation.

    • Hallo Otto and very thank you for the explanation.
      I’ve a couple of questions, if you have time to get back to it.

      I understand the importance to save option values in an array, but how can I manage to achieve the task?

      Also, can we use this same approach to a theme’s options, or just for plugins?

      And not I’m gonna dissect and study your plugins… 😉

      Thansk again, ciao! Carlo

  2. […] tutorial on the WordPress settings API was invaluable for figuring out how to add a settings page the right […]

  3. Great information! I am going to be re-writing the admin section of all of my plugins to use this VS what I’ve got them doing now. Is there anything you need that is needed to change to make the admin options save with ajax?

    Thanks
    -brad

  4. Thanks so much for your article. The WordPress Codex is pretty sparse. If I have a page full of options it can get quite complex by having so many “add_settings_field” functions. It is simple to have just one and make a large section with a single add_settings_field which is what I did for the most part. Thanks again, appreciate your effort!

    Bradford

  5. I’ve seen tutorials about cleaning up after plugins, but not about themes. From what I could find in the source, we still need to “delete_option(‘plugin_options’);” on uninstall.

    I know that plugins have to clean up after themselves with uninstall.php or the uninstall hook. How is it handled with this code? Is it handled automatically with the “register_setting” or “add_settings_field”? And if not, do theme’s support uninstall.php? (I’m assuming yes)

  6. Man, this is awesome. I’ve been looking for that…

  7. […] wanted it to, until I need to add another feature (other option type and validation). I came across Otto’s article about WordPress’ Setting API and it inspired to rerwite the […]

  8. […] Some time ago I wrote a quick tutorial on how to use the Settings API to create your plugins' option pages, and then Otto went deeper in it with a more detailed WordPress Settings API Tutorial. […]

  9. Otto,
    Thanks for the tutorial. I have been able to rewrite most of my options back-end using this, moving from the older approach of creating one’s own forms.

    I have one question, though. How do you tie JavaScript to submit buttons? Basically I have options to save and reset the options, and for the reset I want to add a confirmation upon the clicking of the submit button. I thought that if I had an “onclick” defined for the submit, then made it return false, that should have worked. However it doesn’t seem to be the case. I get the confirmation popup, but even if I decline the action the form submission goes through.

    Any clues? Have you come across this kind of a scenario?

    Sayontan.

  10. What I was looking was the validation thing.

    Do I need to validate every field or just text and textarea fields since nobody can add text strings to radio fields, checkboxes and dropdown lists?

  11. Hey Otto,
    I see you use ‘add_settings_section’ and not ‘add_options_page’. Whats the difference? Which is the “better” way.

    Also, how do I set the default value? For example I’m building a video embed plugin, and I want the default width to be 640px.

    Thanks!

  12. Over a year later, this is still the best tutorial on the Settings API- even a couple of years later. the set up is also most convenient for bringing older setups into the API. I just go back through my form generating function and add name=”options[option1]”. the other methods might be great but would require extensive rewriting of my existing code.

    I have 2 questions though: is it possible to set default values through the API? I have previously used update_option(). and is there a way to reset the db entry? again I’ve used update_option() and just updated it with the default values that I have stored in an object.

    thanks Otto!

    • Is it possible to set default values through the API? Sure, yes. Create a function with an array of default values, then create another function to check if the DB option for these settings is empty, if found empty, the defaults will be stored in.

      Example: declare default options and store them in an array.

      function example_default_options() {
      $options = array(
      'option_a' => 'Example cool value', // string
      'option_b' => 0, // integer
      'option_c' => true, // Boolean
      'option_d' => '' // or NULL
      );
      return $options;
      }

      Example: check if options field (example_options in our example) is not false in the DB. False shows that the field is not used yet or was deleted by someone.


      // Initialize theme options when WP is loaded.
      add_action('wp_loaded', 'cacao_options_setup' );

      /**
      * Set up theme options.
      *
      * @uses get_option() function
      */
      function example_default_options_setup() {

      global $example_options;
      $example_options = get_option( 'example_options' );

      if ( ! $example_options ) {
      $example_options = example_default_options();
      }
      update_option( 'example_options', $example_options );
      }

      Now, check the example_options field from your wp-admin/options.php and you’ll see load of default options filled there.

      Of course you can use after_setup_theme or init to register the action of the default options but they depend on how the file of your options file is loaded. If you loaded the admin file via wp_loaded then after_setup_theme or init, but they work if you loaded file by including in your functions.php file.

      P.S. sorry for my English, its my eighth language 😉

  13. This tutorial is amazing. I’m writing my very first plugin, and your code is helping to ensure that I do as many things correctly as I can.

    I am having one small trouble, however. If I return the $options array, my options don’t get updated. However, if I call update_option using the $options array instead, they do get correctly updated. Do you have any idea where the breakdown might be occurring? I feel like I’m missing a key piece that ties my page to the specific option I am trying to update.

  14. I’m sure I’m the only one, but I eventually determined my error(s) to have been not renaming the second “plugin-options” in “register_setting( ‘plugin_options’, ‘plugin_options’, ‘plugin_options_validate’ );” and subsequently not using the same name (the option name in my wp_options table) for the names of my input fields. Thanks for the great tutorial!

  15. Thanks Otto, this is really helpful.
    I tried it and options page is working great.
    One issue I have is with capabilities.
    I use add_dashboard_page instead of add_options_page (just to add the page as a dashboard submenu).
    I gave at the 3rd parameter the ‘edit_posts’ capability, since I want editors will be able to change options there.
    When I log in with admin, the page is working great, showing page, saving/fetching data etc.
    When I log in with an editor username, I can see the page, but when trying to save the options I get a message that no permissions.
    Thus is since the form action is going through the options.php and editor has no permissions to it.
    How can I grant editor permissions to save this page only?
    If I add the editor capability to ‘manage-options’ he will be able to see all general option pages, and this is not wanted.

    Thanks,
    Maor

  16. […] found this tutorial to be the most concise, and ended up using the code provided as a starting point. Rather than […]

  17. Hello, and thanks for this little tutorial.
    I was used to create all my input field the old fashioned was, as if there was no API at all.
    But thanks to your help I was (and will be) able to fine tune my plugins now.
    But there is one remaining question.
    How to I give feedback to the user about values which didn’t pass the validation tests?
    Normally I check by hand and print out status messages with class=”error”, but I have now idea how to do this now with the API.

  18. […] a lot of you I was reading the tutorials from David Gwyer, Ozh, BobGneu and Otto, but none of them gave proper information on how to pass the error messages to the user when theie […]

  19. […] others such as Otto and Ozh have done yeomen's work in explaining how to implement the Settings API, I have not yet […]

  20. VERY helpful… still not much out there on this subject. This 1 point finally solved hours of research.

    3. You still need to make your own settings whitelisted. To do this, you’ll need to make a call to register_setting. The first argument should be the same as the page name, like ‘general’, or wherever you’re putting your settings. This will let that page recognize and allow your settings to come through.”

    Everything left off how to get my custom field on the General tab to write to the Options table. This made it so easy I figured out to add more to that table so I can then call them back when I need it.

  21. Thank you for this great article. I managed to make a new options page for Counterize. It’s now much simpler to add or modify some options! And now all my settings are recorded into an array.

    A small tip for people who record their options in an array and that one of their option is itself an array (for example using a multi-selection select tag). They can add it like this:

    <select id=’myplugin_select_id’ name=’myplugin_options[option_name][]‘ multiple=’multiple’ size=’10′ style=’height: auto;’>
    

    Where myplugin_options is the name of the options array.

    Regards

  22. One comment on register_setting:

    The output from the validator callback is totally masked, at least in WordPress 3.1.2. Echo, print_r, etc… None of them output anything. I have debug set to true in my wp_config and still nada. The only way I found to output anything was:

    add_settings_error(‘plugin_options’, ‘some_value’, print_r($values, 1), ‘error’);

    BTW – you might want to add a note somewhere in the tutorial about add_settings_error since it’s probably a good idea to use this in the validator. Also from what I can tell the first and second parameters don’t matter much in this basically undocumented function.

    • Yes, the validator runs hidden, and then the page is redirected back to the settings screen. So there’s no easy way to do output there.

      When testing things like this, I tend to use the error_log function to write my debug info to a local file for examination. Like this:

      error_log(var_export($variable,true),3,'/home/user/otto/whatever/debug.txt');
      
  23. I get the error

    PHP Warning: call_user_func() expects parameter 1 to be a valid callback, function ‘plugin_section_text’ not found or invalid function name in E:\Meghtechnologies_wordpress\wp-admin\includes\template.php on line 1160
    PHP Warning: call_user_func() expects parameter 1 to be a valid callback, function ‘plugin_setting_string’ not found or invalid function name in E:\Meghtechnologies_wordpress\wp-admin\includes\template.php on line 1196

  24. I’m following this tutorial to write a theme options page for a theme. I noticed that for the plugin_setting_string() input’s value, you put {$options['text_string']}, but in similar callback functions in my options page, this is generating a parse error: parse error, expecting `’,” or `’;”. When I remove this, the parse error goes away. Is there anyway to use something else for the value?

    • Never mind. I changed the quotes around the echo part to double quotes and used single quotes around the html attributes as well as within the value attribute- just as specified in the tutorial. This works now.

  25. Just wondering if there’s a way to pass some arguments to the callback function of add_settings_field??
    Often you have various fairly similar fields… it’d be heaps easier just passing a string to the callback function!

  26. I was trying to include one of the input values later in my plugin by doing something like $variable = $options[text_string]; and for some reason, whenever I try to use print_r($variable);, it always returns 1…any idea why it would do that?

  27. Kevin – I’ve had a similar problem and turned out I modified the form action (after reading somewhere it should be “”). Check that your form action=”options.php”

  28. Great stuff Otto. The only thing that bothered me whilst reading this was that I would have to repeat this process for every plugin I ever create (even though I probably won’t write many). It just seemed sensible to me to have some kind of a generator, that would pretty much output all the php and html code for you to set however many options you want.

    Since I’m actually much more comfortable with python than with php, I’ve written a small generator in python. It does the (basic) stuff quite well I think… Of course it can be extended and fine-tuned. It’s very rough. But I think it still might useful to create some quick-n-dirty settings pages for plugins…

    #!/usr/bin/env python
    
    # replace with your own unique plugin identifier/name
    plugin_id = "unique_plugin_id"
    
    # This will appear on the settings menu and settings page
    admin_page_menu_desc = "My Plugin"
    admin_page_desc = "My Plugin Settings Page"
    
    # currently, there is only one section.
    section_desc = "Main Settings"
    section_text = "<p> Main description of section, in HTML </p>"
    
    # Here you can define however many fields you want to have. 
    # Each field has 3 properties: field_id, field_name and field_regex for validation
    # Note that the regex is currently fully permissive (i.e. insecure!)
    my_fields = [{'field_id': 'first_name', 'field_name': 'First Name', 'field_regex': '/.*/'}, 
                 {'field_id': 'last_name', 'field_name': 'Last Name', 'field_regex': '/.*/'},
                 {'field_id': 'address', 'field_name': 'Address', 'field_regex': '/.*/'},
                ]
    
    # Nothing to change from here.
    # Simply run this script and it will print out the php code you can add to your plugin.
    #
    # Note that you would still probably need to define field types (if you use checkboxes etc), and most importantly the validation
    # routines. This can be done afterwards, modifying the output of this script.
    
    main_template = """
    <?php 
    // add the admin options page
    add_action('admin_menu', 'plugin_admin_add_page');
    
    function plugin_admin_add_page() {
        add_options_page('%(admin_page_desc)s', '%(admin_page_menu_desc)s', 'manage_options', '%(plugin_id)s', 'plugin_options_page');
    }
    
    // display the admin options page
    function plugin_options_page() { ?>
        <div>
        <h2>%(admin_page_menu_desc)s</h2>
    
        <form action="options.php" method="post">
        <?php settings_fields('%(plugin_id)s_options'); ?>
        <?php do_settings_sections('%(plugin_id)s'); ?>
    
        <input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
        </form></div>
    
    <?php
    }
    
    // add the admin settings and such
    add_action('admin_init', 'plugin_admin_init');
    
    function plugin_admin_init(){
        register_setting( '%(plugin_id)s_options', '%(plugin_id)s_options', 'plugin_options_validate_%(field_id)s' );
        add_settings_section('plugin_main', '%(section_desc)s', 'plugin_section_text', '%(plugin_id)s');
        %(section_fields)s
    }
    
    function plugin_section_text() {
        echo '%(section_text)s';
    } 
    
    %(section_field_callbacks)s
    
    ?>
    """
    
    section_fields_template = """
        add_settings_field('%(field_id)s', '%(field_name)s', 'plugin_setting_%(field_id)s', '%(plugin_id)s', 'plugin_main');
    """
    
    section_field_callbacks_template = """
    
    function plugin_setting_%(field_id)s () {
        $options = get_option('%(plugin_id)s_options');
        echo "<input id='%(field_id)s' name='%(plugin_id)s_options[%(field_id)s]' size='40' type='text' value='{$options['%(field_id)s']}' />";
    }
    // validate our options
    function plugin_options_validate_%(field_id)s($input) {
        $options = get_option('%(plugin_id)s_options');
        // doing per-field regex validation. 
        // You can add / change validation rules here
        foreach ($input as $k => $v) {
            if (preg_match('%(field_regex)s', $v)) {
                $options[$k] = $v;
            }
        }
        return $options;
    }
    """
    
    section_field_callbacks = ""
    section_fields = ""
    for field in my_fields:
        locals().update(field)
        section_field_callbacks += section_field_callbacks_template % locals()
        section_fields += section_fields_template % locals()
    
    print main_template % locals() 
    
  29. Yoav Aner when I try to run your python script I get the following error: SyntaxError: Non-ASCII character ‘\xc3’ in file ./generator on line 101, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

  30. Strange, I just copy&pasted the code from the site into a python file (test.py), and then ran it (python test.py), and it was running fine… Try to check that you copied the code exactly as it is. (I simply used the ‘copy to clipboard’ option on the top right corner of the code).

  31. Sorry – but how to I use a setting set here on a real life (ie – visiable to the end user), and not just as a fancy page for the site admin? Thanks!

  32. […] on the initial page got me hopelessly lost, and it was only when I went through Otto’s WordPress Settings API tutorial that I begin to understand how to implement […]

  33. Hi Otto,

    I’ve created a routine that makes use of your work and allows people to add settings without having to do any coding.
    http://code.olib.co.uk/2011/07/12/wordpress-settings-api-a-quick-implementation/

    Thanks for this page and hope you can make use of my routine.

    Olly

  34. Just wanted to thank you for your comments in the former location of this tutorial at http://ottodestruct.com/blog/2009/wordpress-settings-api-tutorial/ that provided a straightforward method for adding a reset button. In case that page goes away, the submit button & reset button are both type ‘submit’ with names ‘submit’ & ‘reset’, and you check for the presence of $input[‘submit’] or $input[‘reset’] in the validation callback.

  35. […] your options page against changes to the standard UI. I’d also recommend checking out Otto’s Settings API Tutorial for some clear […]

  36. Otto,

    I am in the process of a complete rewrite of my plugin, Events Calendar. I am trying to use the new settings format and I am getting everything to display properly but the options are not saving. What am I missing?


    register_setting( 'events_calendar', 'events_calendar', array( &$validation, 'events_calendar_options' ) );
    add_settings_section( 'events_calendar_main', 'Main Options', array( &$options, 'section_main' ), 'events_calendar' );
    add_settings_field( 'events_calendar_access_level', 'Access Level', array( &$options, 'field_access_level' ), 'events_calendar', 'events_calendar_main' );

    <img src="calendarIcon32.png" />

    <input type="submit" class="button-primary" value="" />


    function field_access_level()
    {
    $options = get_option( 'events_calendar' );
    echo "";
    echo "Administrator";
    echo "Editor";
    echo "Author";
    echo "Contributor";
    echo "Subscriber";
    echo "";
    }

  37. Well that previous comment I left didn’t have all the code. Is there a common problem when options are not saved?

    The part that did not display was basically part of my form. The function that displays the code is in this file.

    http://svn.wp-plugins.org/events-calendar/branches/7.0/classes/class-events-calendar-admin.php

  38. […] It’s very easy to follow and understand, and I highly doubt I could top it so check it out on Ottopress. Saving Data The layout of the WordPress […]

  39. Does anybody know how to implement an upload image functionality?

  40. If we are creating new options to use within a theme, do we need to manually create those options in the database or will it automatically create them when creating this new options page.

  41. I followed the example on this page to create the settings page for my plugin, but I found the Settings API was a little cumbersome (so many callbacks) and not flexible enough for what I wanted. So I wrote a PHP class that turns an array into a settings page. It handles display, editing, and security (nonce and validation). You can still define your own validation callbacks (either globally or per-field) but it comes with a few standard ones (preg_match, url, email, numeric).

    It also (more importantly) handles creation of complex lists (using only one row in wp_options) that might otherwise require creation of a new table.

    The source and a demo plugin are available on my website.

    I hope this is useful to someone.

  42. Thanks for this starter on admin options pages – at least I got a working example now, it has to be refined of course….

  43. yes I have a text box now hehe, hmmm all your knowledge makes my programming knowledge look like …erm like Greece’s economic knowledge

  44. This has been really helpful, even over a year later. Been using this in conjunction with the Twenty Eleven theme to make my own theme settings. I’ve been trying to add a section to include meta-data keywords. Just a simple textarea that would populate the header. Including the textarea in the options page is easy. But for the life of me I can’t figure out how to call it in the rendered page (header.php). Using get_option( ‘plugin_text_string’) returns nothing. Also tried using my own function get_theme_options( ‘plugin_text_string’ ) and at least showed up as “Array.” So how do you get the values from those settings to essentially be echoed to the client’s page?

    • Using the example code above, stuff is stored in the plugin_options option. So code to get it would be $options = get_option(‘plugin_options’);. Then $options would be an array of all the options, and you could reference just one of them with $options[‘text_string’].

      So:

      $options = get_option('plugin_options');
      echo $options['text_string'];
      
      • Thanks for the reply. What I was doing was exactly what you were saying. The difference was that my initial get_option() method was stored inside another function.

        function bgtbp_get_theme_options() {
        return get_option( 'bgtbp_theme_options', bgtbp_get_default_theme_options() );
        }

        My hope was to simply echo out bgtbp_get_theme_options() as $key/$value pairs but that didn’t work. So I took your suggestion and ended up making a separate function for each $key. A bit more work than I initially hoped but it works. Thanks

  45. otto i am trying to create a drop down list of pages to select a particular page for me to use as a featured item in my themes front page – i’ve been using your tutorial to implement text areas and input fields into the settings page – is there any difference when using a drop down list?

    if so how do you store them in your option array?

  46. thank for this great tutorial… it save me a lot of time and more decent tut and easy to understand than the wordpress documentation. I wonder if i can create multipage using the functions you’ve given…

    thanks a lot… keep posting…. 🙂

  47. hi Otto.. after reading your article and trying it, it all works perfectly.I use it as a guide in developing a wordpress plugin due to its very decent implementation of codes and well documented. Actually, i already started developed my first plugin and done a lot of codes, after seeing this tutorial, its quite nice to follow different to my past works which is more on including php files to an external directory.
    I wonder if you can suggest how to include jquery and ajax that handle the actions in the form input fileds instead of using the . I already use some codes to call javascript but its difficult from my side to implement inside wordpress.

    //— I try this line but this action works only under admin settings menu. correct me if i’m wrong.. i confuse if i could use this code calling the buttons or input fields actions and pass the actions into other page and do some stuff.

    function th_admin_head() {
    $plugindir = get_settings(‘home’).’/wp-content/plugins/’.dirname(plugin_basename(__FILE__));
    wp_enqueue_script(‘loadjs’, $plugindir . ‘/js/ajax.js’);
    }

    add_action( “admin_print_scripts-$th_menu_page”, ‘th_admin_head’ );

    And also i try the lines below but it didnt recognized in wordpress. i dunno if this really works.
    wp_enqueue_script(‘home’, get_bloginfo(‘template_directory’) . ‘/scripts/sample.js’, array(‘jquery’, ‘jquery-ui-core’, ‘jquery-ui-tabs’), ‘1.0’);

    I also try some plugin directory url functions but it so many things to consider. I done some of this that works but it conflict to other plugins and crashed.

    A little help will be greatly appreciated..thanks…
    more power… 😀

  48. hi Otto.. after reading your article and trying it, it all works perfectly.I use it as a guide in developing a wordpress plugin due to its very decent implementation of codes and well documented. Actually, i already started developed my first plugin and done a lot of codes, after seeing this tutorial, its quite nice to follow different to my past works which is more on including php files to an external directory.
    I wonder if you can suggest how to include jquery and ajax that handle the actions in the form input fileds instead of using the . I already use some codes to call javascript but its difficult from my side to implement inside wordpress.

    //— I try this line but this action works only under admin settings menu. correct me if i’m wrong.. i confuse if i could use this code calling the buttons or input fields actions and pass the actions into other page and do some stuff.

    function th_admin_head() {
    $plugindir = get_settings(‘home’).’/wp-content/plugins/’.dirname(plugin_basename(__FILE__));
    wp_enqueue_script(‘loadjs’, $plugindir . ‘/js/ajax.js’);
    }

    add_action( “admin_print_scripts-$th_menu_page”, ‘th_admin_head’ );

    And also i try the lines below but it didnt recognized in wordpress. i dunno if this really works.
    wp_enqueue_script(‘home’, get_bloginfo(‘template_directory’) . ‘/scripts/sample.js’, array(‘jquery’, ‘jquery-ui-core’, ‘jquery-ui-tabs’), ’1.0′);

    I also try some plugin directory url functions but it so many things to consider. I done some of this that works but it conflict to other plugins and crashed.

    A little help will be greatly appreciated..thanks…
    more power… 😀

  49. This was a great tutorial.. Thanks so much

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Need to post PHP code? Wrap it in [php] and [/php] tags.