Settings API – save multiple tabs at once

Don’t initialize defaults, or do an initial save. Just use sane defaults.

For example, define an array of defaults:

function wpse92323_get_option_defaults() {
    $defaults = array(
        'slug1' => 'default1',
        'slug2' => 'default2'
    );
    return apply_filters( 'wpse92323_option_defaults', $defaults );
}

Then, write a function to return an option value, that parses stored options against your defaults:

function wpse92323_get_options() {

    // Get the option defaults
    $option_defaults = wpse92323_get_option_defaults();
    // Globalize the variable that holds the Theme options
    global $wpse92323_options;
    // Parse the stored options with the defaults
    $wpse92323_options = wp_parse_args( get_option( 'theme_wpse92323_options', array() ), $option_defaults );
    // Return the parsed array
    return $wpse92323_options;
}

Then, everywhere you use your options:

// Get options
global $wpse92323_options;
$wpse92323_options = wpse92323_get_options();

// Echo an option
echo $wpse92323_options['slug1']

Explanation of wpse92323_get_options():

  1. wp_parse_args( $args, $defaults ): will parse two arrays, $args, and $defaults, with any keys in $args overriding the same keys in $defaults
  2. get_option( 'theme_wpse92323_options', array() ): returns the value of a stored option. (Replace 'theme_wpse92323_options' with whatever you call in register_setting().) The second parameter is the default value; passing array() ensures that, if the option hasn’t yet been set, an empty array is returned. (This is critical for the use of wp_parse_args().)

So, what this construct does:

  1. Get the current Theme options array
  2. If it isn’t yet set, return an empty array
  3. Parse the current Theme options array against the option defaults, letting the user-defined Theme options take precedence
  4. Return the resulting, merged array

Using this method, the user or Theme never actually has to save any Theme option values to the database in order for the Theme to work properly. The Theme works properly, with defined, sane defaults, “out of the box”.