WordPress theme options and insert default value for serialize data

Loop over your array of options and generate a set of defaults from that..

Let’s imagine your array looks something like this.. (but obviously bigger)..

$your_options = array(  
    array( 
        'name' => 'option-one',
        'desc' => 'Option one description',
        'type' => 'text',
        'std'  => 'default_value'
    ),
    ..and so on.. for each option..
);

First check if you have options, if not, it’s the first install so you can set defaults.

$my_var_that_holds_options = get_option( 'your_theme_options_name' );
if( !$my_var_that_holds_options ) {
    // Do code to setup defaults
}

The code to setup defaults will of course go where i’ve put // Do code to setup defaults.

First, create an array to hold the defaults and loop over the options array to build the new defaults array.

$defaults = array();
foreach( $your_options_var as $option_data ) {
    $defaults[$option_data['name']] = $option_data['std'];
}

By the end you’ll have an array of option names and default values, which you can then send to the database.

update_option( 'your_theme_options_name', $defaults );

If you code needs to loop over the options to set boxes checked, etc.. simply call get_option again after you’ve saved the defaults..

$my_var_that_holds_options = get_option( 'your_theme_options_name' );

Or use the defaults array.

$my_var_that_holds_options = $defaults;

I’ve had to be quite general with the example, because the approach will differ depending on how your options array is structured.

The important factor here is to ensure your array of options holds a “default” value(std in the example) for each option else you’ve got nothing to form your default values from.

I’ve converted themes to do this a handful of times, if you have trouble implementing this feel free to pastebin your file with the options array and i’ll take a look.