• Options API, Settings API
  • Complete Plugin Management Page
  • Example Using Transients API
  • per - user settings

The Options API is a set of functions that enable easy access to the database where WordPress, plugins, and themes save and fetch needed information. Options are stored in a database table named, by default, wp_options and can be text, integers, arrays, or objects.

THE SETTINGS API- Options can be internally created and updated by your plugin, But they are also frequently used to store settings the end user will modify through your plugin administration page. Dealing with user inputs introduces new constraints in the option process: You need to design a user interface, monitor form submissions, handle security checks, and validate user inputs. To easily manage these common tasks, WordPress wraps the option functions into a comprehensive Settings API.

Complete Plugin Management Page:

<?php
/*
Plugin Name: Settings API example
Plugin URI: http://example.com/
Description: A complete and practical example of use of the Settings API. This plugin creates a new plugin administration page.
*/
 
// Add a menu for our option page
add_action('admin_menu', 'ssd_myplugin_add_page');
function ssd_myplugin_add_page() {
    add_options_page( 'My Plugin', 'My Plugin', 'manage_options', 'ssd_myplugin', 'ssd_myplugin_option_page' );
}
 
// Draw the option page
function ssd_myplugin_option_page() {
    ?>
    <div class="wrap">
        <?php screen_icon(); ?>
        <h2>My plugin</h2>
        <form action="options.php" method="post">
            <?php settings_fields('ssd_myplugin_options'); ?>
            <?php do_settings_sections('ssd_myplugin'); ?>
            <input name="Submit" type="submit" value="Save Changes" />
        </form>
    </div>
    <?php
}
 
// Register and define the settings
add_action('admin_init', 'ssd_myplugin_admin_init');
function ssd_myplugin_admin_init(){
    register_setting(
        'ssd_myplugin_options',
        'ssd_myplugin_options',
        'ssd_myplugin_validate_options'
    );
    add_settings_section(
        'ssd_myplugin_main',
        'My Plugin Settings',
        'ssd_myplugin_section_text',
        'ssd_myplugin'
    );
    add_settings_field(
        'ssd_myplugin_text_string',
        'Enter text here',
        'ssd_myplugin_setting_input',
        'ssd_myplugin',
        'ssd_myplugin_main'
    );
}
 
// Draw the section header
function ssd_myplugin_section_text() {
    echo '<p>Enter your settings here.</p>';
}
 
// Display and fill the form field
function ssd_myplugin_setting_input() {
    // get option 'text_string' value from the database
    $options = get_option( 'ssd_myplugin_options' );
    $text_string = $options['text_string'];
    // echo the field
    echo "<input id='text_string' name='ssd_myplugin_options[text_string]' type='text' value='$text_string' />";
}
 
// Validate user input (we want text only)
function ssd_myplugin_validate_options( $input ) {
    $valid['text_string'] = preg_replace( '/[^a-zA-Z]/', '', $input['text_string'] );
 
    if( $valid['text_string'] != $input['text_string'] ) {
        add_settings_error(
            'ssd_myplugin_text_string',
            'ssd_myplugin_texterror',
            'Incorrect value entered!',
            'error'
        );        
    }
 
    return $valid;
}

The validation function you ’ ve previously defi ned could be slightly improved by letting the users know they have entered an unexpected value and that it has been modifi ed so that they can pay attention to it and maybe amend their input. The relatively unknown function add_settings_error() of the Settings API can handle this case. Your previous plugin was adding a whole new section and its input fi eld on a standalone page: You now modify it to insert this content into WordPress ’ Privacy Settings page. Of course, it can even make sense to add just one fi eld and no section header to an existing page.

Adding a Section to an Existing Page

<?php
/*
Plugin Name: Settings API example 2
Plugin URI: http://example.com/
Description: A complete and practical example of use of the Settings API. This one adds a field to the Privacy Settings page
*/
 
// Register and define the settings
add_action('admin_init', 'ssd_myplugin_admin_init');
function ssd_myplugin_admin_init(){
    register_setting(
        'privacy', 
        'ssd_myplugin_options',
        'ssd_myplugin_validate_options' 
    );
 
    add_settings_field(
        'ssd_myplugin_text_string',
        'Enter text here',
        'ssd_myplugin_setting_input',
        'privacy',
        'default'
    );
 
}
 
// Display and fill the form field
function ssd_myplugin_setting_input() {
    // get option 'text_string' value from the database
    $options = get_option( 'ssd_myplugin_options' );
    $text_string = $options['text_string'];
    // echo the field
    echo "<input id='text_string' name='ssd_myplugin_options[text_string]' type='text' value='$text_string' />";
}
 
// Validate user input (we want text only)
function ssd_myplugin_validate_options( $input ) {
    $valid['text_string'] = preg_replace( '/[^a-zA-Z]/', '', $input['text_string'] );
 
    if( $valid['text_string'] != $input['text_string'] ) {
        add_settings_error(
            'ssd_myplugin_text_string',
            'ssd_myplugin_texterror',
            'Incorrect value entered!',
            'error'
        );        
    }
 
    return $valid;
}

Example Using Transients API

<?php
/*
Plugin Name: Transients API example
Plugin URI: http://example.com/
Description: Sample plugin to illustrate how the Transients API works.
*/
 
// Fictional function that fetchs from an online radio a song title currently on air
function ssd_myplugin_fetch_song_title_from_radio() {
    /*
    Here you would find code fetching data from a remote web site.
    See Chapter 10 to learn how to do this.
 
    In this example we will just return a random song title from a few fictional ones
    */
 
    $titles = array(
        'I Heart WordPress - by  Hackers',
        'Highway to Heaven - by AB/CD',
        'WorpDress Roks - by Miss Spellings',
        'Careful With That Hack, Eugene - by Fink Ployd'
    );
 
    // Get a random song title and return it
    $random = $titles[ mt_rand(0, count($titles) - 1) ];
    return $random;
}
 
// Get song title from database and return it
function ssd_myplugin_get_song_title() {
 
    // Get transient value
    $title = get_transient( 'ssd_myplugin_song' );
 
    // If the transient does not exists or has expired, refresh it
    if( false === $title ) {
        $title = ssd_myplugin_fetch_song_title_from_radio();
        set_transient( 'ssd_myplugin_song', $title, 180 );
    }
 
    return $title;
}

Admin Lang Plugin

<?php
/*
Plugin Name: Per User Setting example
Plugin URI: http://example.com/
Description: Add a user option in Profile to allow choosing either English or Spanish in the admin area
 
*/
 
// Return user's locale
function ssd_adminlang_set_user_locale() {
    $user = wp_get_current_user();
    $userid = $user->ID;
    $locale = get_user_meta( $userid, 'ssd_adminlang_lang', true );
    return $locale;
}
// Trigger this function every time WP checks the locale value
add_filter( 'locale', 'ssd_adminlang_set_user_locale' );
 
// Add and fill an extra input field to user's profile
function ssd_adminlang_display_field( $user ) {
 
    $userid = $user->ID;
    $lang = get_user_meta( $userid, 'ssd_adminlang_lang', true );
 
    ?>
    <tr>
        <th scope="row">Language</th>
        <td>
            <select name="ssd_adminlang_lang">
                <option value="" <?php selected( '', $lang); ?>>English</option>
                <option value="es_ES" <?php selected( 'es_ES', $lang); ?>>Espa&ntilde;ol</option>
            </select>
        </td>
    </tr>
    <?php
}
add_action( 'personal_options', 'ssd_adminlang_display_field' );
 
// Monitor form submits and update user's setting if applicable
function ssd_adminlang_update_field( $userid ) {
    if( isset( $_POST['ssd_adminlang_lang'] ) ) {
        $lang = $_POST['ssd_adminlang_lang'] == 'es_ES' ? 'es_ES' : '';
        update_user_meta( $userid, 'ssd_adminlang_lang', $lang );
    }
}
add_action( 'personal_options_update', 'ssd_adminlang_update_field' );

For this plugin to work, the WordPress installation needs to include the Spanish translation fi les you can get from http://es.wordpress.org/ . Put the es_ES fi les in the directory wp - content/languages (which you might need to create fi rst).

Leave a Comment

Fields with * are required.

Please enter the letters as they are shown in the image above.
Letters are not case-sensitive.